/**
 * Interactive PDF Form Filling - Adobe Style
 */

jQuery(document).ready(function($) {
    'use strict';
    
    // Debug logging - only in development
    const PSF_DEBUG = window.swpdfDevMode && window.swpdfDevMode.enabled;
    function swpdfLog(...args) {
        if (PSF_DEBUG) console.log('[PSF]', ...args);
    }
    
    let pdfDoc = null;
    let currentPage = 1;
    let totalPages = 0;
    let pdfFields = [];
    let currentFieldIndex = 0;
    let formData = {};
    let signaturePad = null;
    let pdfTemplate = null;
    let gatedEmail = null; // Stores email from gate
    
    // Set PDF.js worker
    pdfjsLib.GlobalWorkerOptions.workerSrc = swpdfSignature.pdfjsWorker;
    
    /**
     * Initialize
     */
    function init() {
        swpdfLog('PDF Sign & Fill: Initializing...');
        swpdfLog('Agreement type:', $('#psf-signature-form').data('agreement-type'));
        
        // Hide auto-detect button since it's automatic now
        $('#auto-detect-fields').hide();
        
        // Check if email gate is present
        if ($('#email-gate').length) {
            bindEmailGate();
        } else {
            loadPDFTemplate();
        }
        
        bindEvents();
    }
    
    /**
     * Email Gate Handler
     */
    function bindEmailGate() {
        $('#gate-continue').on('click', function() {
            const email = $('#gate-email').val().trim();
            
            if (!email || !isValidEmail(email)) {
                $('#gate-email').css('border-color', '#dc3545');
                alert('Please enter a valid email address');
                return;
            }
            
            gatedEmail = email;
            $('#email-gate').fadeOut(300, function() {
                $('.pdf-interactive-section').fadeIn(300);
                loadPDFTemplate();
            });
        });
        
        // Allow Enter key to submit
        $('#gate-email').on('keypress', function(e) {
            if (e.which === 13) {
                $('#gate-continue').click();
            }
        });
    }
    
    function isValidEmail(email) {
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
    }
    
    /**
     * Load PDF Template
     */
    function loadPDFTemplate() {
        const agreementType = String($('#psf-signature-form').data('agreement-type') || '').toLowerCase();
        swpdfLog('Loading PDF template for:', agreementType);
        
        $.ajax({
            url: swpdfSignature.ajaxUrl,
            type: 'POST',
            data: {
                action: 'swpdf_get_pdf_template',
                agreement_type: agreementType,
                nonce: swpdfSignature.nonce
            },
            success: function(response) {
                swpdfLog('Template response:', response);
                if (response.success && response.data.template) {
                    pdfTemplate = response.data.template;
                    swpdfLog('Template loaded:', pdfTemplate);
                    
                    // Store custom field labels if available
                    if (pdfTemplate.field_labels) {
                        window.customFieldLabels = pdfTemplate.field_labels;
                        swpdfLog('Custom field labels loaded:', window.customFieldLabels);
                    }
                    
                    // Store required fields
                    if (pdfTemplate.field_required) {
                        window.fieldRequired = pdfTemplate.field_required;
                        swpdfLog('Required fields loaded:', window.fieldRequired);
                    }
                    
                    // Store saved fields list (only these fields will be shown)
                    if (pdfTemplate.fields_list) {
                        window.savedFieldsList = pdfTemplate.fields_list;
                        swpdfLog('Saved fields list loaded:', window.savedFieldsList);
                    }
                    
                    // Store signature position settings
                    if (pdfTemplate.signature_settings) {
                        window.signatureSettings = pdfTemplate.signature_settings;
                        swpdfLog('Signature settings loaded:', window.signatureSettings);
                    }
                    
                    // Store date position settings
                    if (pdfTemplate.date_settings) {
                        window.dateSettings = pdfTemplate.date_settings;
                        swpdfLog('Date settings loaded:', window.dateSettings);
                    }
                    
                    // Add cache-busting to ensure fresh PDF is loaded
                    const cacheBuster = '?v=' + Date.now();
                    displayPDF(swpdfSignature.templatesUrl + pdfTemplate.filename + cacheBuster);
                } else {
                    console.error('Template not found:', response);
                    showMessage('PDF template not found: ' + (response.data ? response.data.message : 'Unknown error'), 'error');
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX error:', status, error);
                showMessage('Error loading PDF template', 'error');
            }
        });
    }
    
    /**
     * Display PDF
     */
    async function displayPDF(url) {
        try {
            swpdfLog('Loading PDF from:', url);
            const loadingTask = pdfjsLib.getDocument(url);
            pdfDoc = await loadingTask.promise;
            swpdfLog('PDF loaded, pages:', pdfDoc.numPages);
            
            totalPages = pdfDoc.numPages;
            $('#total-pages').text(totalPages);
            
            await renderPage(currentPage);
            swpdfLog('First page rendered');
            
            // Auto-detect fields immediately after PDF loads
            await autoDetectFields();
            swpdfLog('Auto-detect completed');
            
        } catch (error) {
            console.error('Error loading PDF:', error);
            showMessage('Error loading PDF: ' + error.message, 'error');
        }
    }
    
    /**
     * Render PDF Page
     */
    async function renderPage(pageNum) {
        const page = await pdfDoc.getPage(pageNum);
        const canvas = document.getElementById('pdf-canvas');
        const context = canvas.getContext('2d');
        
        // Make responsive for mobile
        const containerWidth = $('#pdf-container').width() || window.innerWidth - 40;
        const viewport = page.getViewport({ scale: 1.5 });
        const scale = Math.min(1.5, containerWidth / viewport.width);
        const scaledViewport = page.getViewport({ scale: scale });
        
        canvas.width = scaledViewport.width;
        canvas.height = scaledViewport.height;
        
        const renderContext = {
            canvasContext: context,
            viewport: scaledViewport
        };
        
        await page.render(renderContext).promise;
        
        currentPage = pageNum;
        $('#current-page').text(pageNum);
        
        // Update navigation
        $('#prev-page').prop('disabled', pageNum <= 1);
        $('#next-page').prop('disabled', pageNum >= totalPages);
    }
    
    /**
     * Auto-Detect PDF Form Fields
     */
    async function autoDetectFields() {
        pdfFields = [];
        
        // Get saved fields list (if admin deleted some fields, only show remaining ones)
        const savedFields = window.savedFieldsList || null;
        const savedFieldNames = savedFields ? savedFields.map(f => f.name) : null;
        const requiredFields = window.fieldRequired || {};
        
        // Separate manual fields (those with isManual flag and position data)
        const manualFieldsMap = {};
        if (savedFields) {
            savedFields.forEach(function(f) {
                if (f.isManual && f.position) {
                    manualFieldsMap[f.name] = f;
                }
            });
        }
        
        try {
            // Loop through all pages
            for (let i = 1; i <= totalPages; i++) {
                const page = await pdfDoc.getPage(i);
                const annotations = await page.getAnnotations();
                
                // Calculate responsive scale
                const containerWidth = $('#pdf-container').width() || window.innerWidth - 40;
                const baseViewport = page.getViewport({ scale: 1.5 });
                const scale = Math.min(1.5, containerWidth / baseViewport.width);
                const viewport = page.getViewport({ scale: scale });
                
                // First, add PDF form fields (annotations)
                annotations.forEach(function(annotation) {
                    if (annotation.fieldType && annotation.fieldName) {
                        // Skip fields that were deleted in admin (not in saved fields list)
                        if (savedFieldNames && !savedFieldNames.includes(annotation.fieldName)) {
                            swpdfLog('Skipping deleted field:', annotation.fieldName);
                            return;
                        }
                        
                        // Skip date fields - they will be auto-filled
                        const dateFieldNames = ['Date', 'Date_', 'date', 'date_', 'SignatureDate', 'Signature_Date', 'Date_2', 'Today', 'today', 'CurrentDate', 'current_date'];
                        const fieldNameLower = annotation.fieldName.toLowerCase();
                        if (dateFieldNames.some(df => df.toLowerCase() === fieldNameLower) || fieldNameLower.includes('date')) {
                            swpdfLog('Skipping date field (auto-fill):', annotation.fieldName);
                            return;
                        }
                        
                        // Skip signature fields - handled separately
                        if (fieldNameLower.includes('signature') || fieldNameLower.includes('sig_') || fieldNameLower === 'sig') {
                            swpdfLog('Skipping signature field:', annotation.fieldName);
                            return;
                        }
                        
                        // Calculate field position
                        const rect = annotation.rect;
                        const [x1, y1, x2, y2] = rect;
                        
                        // Use custom label if available, otherwise use field name
                        let fieldLabel = annotation.fieldName.replace(/_/g, ' ');
                        if (window.customFieldLabels && window.customFieldLabels[annotation.fieldName]) {
                            fieldLabel = window.customFieldLabels[annotation.fieldName];
                        }
                        
                        // Check if required
                        const isRequired = requiredFields[annotation.fieldName] === true;
                        
                        pdfFields.push({
                            name: annotation.fieldName,
                            label: fieldLabel,
                            required: isRequired,
                            page: i,
                            x: x1 * viewport.scale,
                            y: viewport.height - (y2 * viewport.scale),
                            width: (x2 - x1) * viewport.scale,
                            height: (y2 - y1) * viewport.scale,
                            value: ''
                        });
                    }
                });
                
                // Then, add manual fields for this page
                Object.keys(manualFieldsMap).forEach(function(fieldName) {
                    const manualField = manualFieldsMap[fieldName];
                    if (manualField.page === i) {
                        // Use custom label if available
                        let fieldLabel = fieldName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
                        if (window.customFieldLabels && window.customFieldLabels[fieldName]) {
                            fieldLabel = window.customFieldLabels[fieldName];
                        }
                        
                        const isRequired = requiredFields[fieldName] === true;
                        const pos = manualField.position;
                        
                        pdfFields.push({
                            name: fieldName,
                            label: fieldLabel,
                            required: isRequired,
                            page: i,
                            x: pos.x * viewport.scale,
                            y: viewport.height - ((pos.y + pos.height) * viewport.scale),
                            width: pos.width * viewport.scale,
                            height: pos.height * viewport.scale,
                            value: '',
                            isManual: true
                        });
                        swpdfLog('Added manual field:', fieldName, 'on page', i);
                    }
                });
            }
            
            swpdfLog('Fields to show:', pdfFields.length);
            
            if (pdfFields.length > 0) {
                $('#start-filling').show();
                renderFieldOverlays();
            } else {
                showMessage('No fillable fields detected in this PDF.', 'warning');
            }
            
        } catch (error) {
            console.error('Error detecting fields:', error);
        }
    }
    
    /**
     * Manual Auto-Detect button (kept for backup)
     */
    $('#auto-detect-fields').on('click', async function() {
        await autoDetectFields();
        
        if (pdfFields.length === 0) {
            showMessage('No fillable fields detected in this PDF.', 'warning');
        } else {
            showMessage(`Found ${pdfFields.length} fields!`, 'success');
        }
    });
    
    /**
     * Render Field Overlays on PDF
     */
    function renderFieldOverlays() {
        const overlay = $('#pdf-field-overlay');
        overlay.empty();
        
        // Only show fields for current page
        pdfFields.forEach(function(field, index) {
            if (field.page === currentPage) {
                // Check if this is the current field being edited
                const isCurrentField = (index === currentFieldIndex);
                
                const fieldDiv = $('<div>')
                    .addClass('pdf-field-marker')
                    .attr('data-field-index', index)
                    .css({
                        position: 'absolute',
                        left: field.x + 'px',
                        top: field.y + 'px',
                        width: field.width + 'px',
                        height: field.height + 'px',
                        border: isCurrentField ? '4px solid #ff6600' : (field.value ? '2px solid #00cc00' : '2px dashed #0066cc'),
                        background: field.value ? 'rgba(255, 255, 255, 0.95)' : (isCurrentField ? 'rgba(255, 102, 0, 0.2)' : 'rgba(0, 102, 204, 0.1)'),
                        cursor: 'pointer',
                        fontSize: '14px',
                        fontWeight: field.value ? '600' : 'normal',
                        padding: '4px 6px',
                        color: '#000',
                        display: 'flex',
                        alignItems: 'center',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                        boxShadow: isCurrentField ? '0 0 20px rgba(255, 102, 0, 0.8), 0 0 40px rgba(255, 102, 0, 0.4)' : 'none',
                        zIndex: isCurrentField ? 100 : 1,
                        animation: isCurrentField ? 'pulse-field 1.5s ease-in-out 3' : 'none'
                    })
                    .text(field.value || '');
                
                // Add "YOU ARE HERE" indicator for current field
                if (isCurrentField) {
                    const indicator = $('<div>')
                        .css({
                            position: 'absolute',
                            top: '-35px',
                            left: '50%',
                            transform: 'translateX(-50%)',
                            background: '#ff6600',
                            color: 'white',
                            padding: '5px 12px',
                            borderRadius: '4px',
                            fontSize: '12px',
                            fontWeight: 'bold',
                            whiteSpace: 'nowrap',
                            boxShadow: '0 2px 8px rgba(0,0,0,0.3)',
                            zIndex: 101
                        })
                        .html('👉 Fill this field');
                    
                    fieldDiv.append(indicator);
                }
                
                overlay.append(fieldDiv);
            }
        });
    }
    
    /**
     * Start Filling Form
     */
    $('#start-filling').on('click', function() {
        if (pdfFields.length === 0) {
            showMessage('No fields detected', 'error');
            return;
        }
        
        currentFieldIndex = 0;
        showFieldInput(0);
    });
    
    /**
     * Show Field Input
     */
    function showFieldInput(fieldIndex) {
        if (fieldIndex < 0 || fieldIndex >= pdfFields.length) {
            // All fields filled - validate required fields before proceeding
            const missingRequired = pdfFields.filter(f => f.required && !f.value);
            if (missingRequired.length > 0) {
                const fieldNames = missingRequired.map(f => f.label).join(', ');
                showMessage('Please fill required fields: ' + fieldNames, 'error');
                // Go to first missing required field
                const firstMissing = pdfFields.findIndex(f => f.required && !f.value);
                currentFieldIndex = firstMissing;
                showFieldInput(firstMissing);
                return;
            }
            
            // All fields filled - show review before signature
            $('#current-field-input').hide();
            showReviewScreen();
            return;
        }
        
        const field = pdfFields[fieldIndex];
        
        // Navigate to field's page
        if (field.page !== currentPage) {
            renderPage(field.page);
        }
        
        // Update input with required indicator
        const requiredMark = field.required ? ' <span style="color: red;">*</span>' : '';
        $('#field-label').html(field.label + requiredMark);
        $('#field-input').val(field.value);
        
        // Update placeholder
        $('#field-input').attr('placeholder', field.required ? 'Required - Type here...' : 'Type here...');
        
        $('#field-progress').html(`Field ${fieldIndex + 1} of ${pdfFields.length} <span style="color: #999; font-size: 13px;">(Page ${field.page})</span>`);
        
        // Add big visual indicator showing EXACTLY which field
        const fieldInfo = $('<div>')
            .attr('id', 'current-field-indicator')
            .css({
                position: 'absolute',
                top: '20px',
                left: '50%',
                transform: 'translateX(-50%)',
                background: '#ff6600',
                color: 'white',
                padding: '15px 30px',
                borderRadius: '8px',
                fontSize: '18px',
                fontWeight: 'bold',
                boxShadow: '0 4px 12px rgba(0,0,0,0.3)',
                zIndex: 1000,
                animation: 'bounce 0.5s ease-in-out 2',
                pointerEvents: 'none'
            })
            .html('👇 Filling: ' + field.label + ' (Page ' + field.page + ')');
        
        $('#pdf-field-overlay').find('#current-field-indicator').remove();
        $('#pdf-field-overlay').append(fieldInfo);
        
        // Show/hide navigation buttons
        $('#prev-field').prop('disabled', fieldIndex === 0);
        
        $('#current-field-input').fadeIn();
        $('#field-input').focus();
        
        // Highlight current field on PDF
        highlightCurrentField(fieldIndex);
        
        // Update progress summary
        updateProgressSummary();
    }
    
    /**
     * Highlight Current Field
     */
    function highlightCurrentField(fieldIndex) {
        // Reset all fields
        $('.pdf-field-marker').css({
            'border': '2px dashed #0066cc',
            'animation': 'none',
            'box-shadow': 'none',
            'z-index': '1'
        });
        
        // Highlight current field with pulsing animation
        const currentField = $('.pdf-field-marker').filter(function() {
            return $(this).data('field-index') === fieldIndex;
        });
        
        currentField.css({
            'border': '4px solid #ff6600',
            'animation': 'pulse-field 1.5s ease-in-out 3',
            'box-shadow': '0 0 20px rgba(255, 102, 0, 0.6)',
            'z-index': '10'
        });
        
        // Scroll field into view
        if (currentField.length > 0) {
            const canvas = $('#pdf-canvas')[0];
            const canvasRect = canvas.getBoundingClientRect();
            const fieldOffset = currentField.offset();
            const containerOffset = $('#pdf-viewer').offset();
            
            $('#pdf-viewer').animate({
                scrollTop: $('#pdf-viewer').scrollTop() + (fieldOffset.top - containerOffset.top) - 100
            }, 500);
        }
    }
    
    /**
     * Next Field
     */
    $('#next-field').on('click', function() {
        // Save current field value
        const fieldValue = $('#field-input').val().trim();
        const currentField = pdfFields[currentFieldIndex];
        
        // Check if required field is empty
        if (currentField.required && !fieldValue) {
            showMessage('This field is required. Please fill it before continuing.', 'error');
            $('#field-input').focus();
            return;
        }
        
        currentField.value = fieldValue;
        
        if (fieldValue) {
            formData[currentField.name] = fieldValue;
        }
        
        // Update overlay
        renderFieldOverlays();
        
        // Update progress summary
        updateProgressSummary();
        
        // Move to next field
        currentFieldIndex++;
        showFieldInput(currentFieldIndex);
    });
    
    /**
     * Update Progress Summary
     */
    function updateProgressSummary() {
        let summaryHtml = '';
        let filledCount = 0;
        
        pdfFields.forEach(function(field) {
            if (field.value) {
                filledCount++;
                summaryHtml += '<div style="margin-bottom: 8px; padding: 8px; background: #f0f9ff; border-left: 3px solid #0066cc; border-radius: 3px;">';
                summaryHtml += '<strong style="color: #0066cc;">' + field.label + '</strong><br>';
                summaryHtml += '<span style="color: #333;">' + field.value + '</span>';
                summaryHtml += '</div>';
            }
        });
        
        if (summaryHtml === '') {
            summaryHtml = '<p style="color: #999;">Start filling to see your progress...</p>';
        } else {
            summaryHtml = '<div style="margin-bottom: 10px; font-weight: 600; color: #0066cc;">' + 
                          filledCount + ' of ' + pdfFields.length + ' fields completed</div>' + summaryHtml;
        }
        
        $('#filled-fields-summary').html(summaryHtml);
    }
    
    /**
     * Previous Field
     */
    $('#prev-field').on('click', function() {
        currentFieldIndex--;
        showFieldInput(currentFieldIndex);
    });
    
    /**
     * Enter key = Next
     */
    $('#field-input').on('keypress', function(e) {
        if (e.which === 13) {
            e.preventDefault();
            $('#next-field').click();
        }
    });
    
    /**
     * Show Review Screen
     */
    async function showReviewScreen() {
        try {
            showMessage('Generating preview...', 'info');
            const pdfData = await generateFilledPDFPreview(formData);

            if (!pdfData) {
                return;
            }

            // Store for rendering
            window.reviewPdfData = pdfData;

            let reviewHtml = '<div style="max-width: 950px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px;">';
            reviewHtml += '<h2 style="margin-top: 0; text-align: center;">📄 Review Your Document</h2>';
            
            // Zoom controls
            reviewHtml += '<div style="text-align: center; margin-bottom: 15px; padding: 10px; background: #f5f5f5; border-radius: 6px;">';
            reviewHtml += '<span style="font-weight: 600; margin-right: 15px;">🔍 ZOOM:</span>';
            reviewHtml += '<button type="button" id="review-zoom-out" class="btn btn-secondary btn-small" style="padding: 5px 15px; margin: 0 5px;">−</button>';
            reviewHtml += '<span id="review-zoom-level" style="display: inline-block; min-width: 60px; text-align: center; font-weight: bold;">100%</span>';
            reviewHtml += '<button type="button" id="review-zoom-in" class="btn btn-secondary btn-small" style="padding: 5px 15px; margin: 0 5px;">+</button>';
            reviewHtml += '<button type="button" id="review-zoom-fit" class="btn btn-secondary btn-small" style="padding: 5px 15px; margin-left: 15px;">Fit</button>';
            reviewHtml += '<span style="margin-left: 20px; color: #666; font-size: 13px;">👆 Drag to pan when zoomed</span>';
            reviewHtml += '</div>';
            
            // Page navigation controls
            reviewHtml += '<div id="review-page-controls" style="text-align: center; margin-bottom: 10px; display: none;">';
            reviewHtml += '<button type="button" id="review-prev-page" class="btn btn-secondary btn-small" style="padding: 5px 15px;">◀ Previous</button>';
            reviewHtml += '<span id="review-page-info" style="display: inline-block; min-width: 120px; text-align: center; font-weight: bold; margin: 0 15px;">Page 1 of 1</span>';
            reviewHtml += '<button type="button" id="review-next-page" class="btn btn-secondary btn-small" style="padding: 5px 15px;">Next ▶</button>';
            reviewHtml += '</div>';
            
            // PDF viewer container with canvas
            reviewHtml += '<div id="review-pdf-container" style="margin: 15px 0; border: 2px solid #ddd; border-radius: 4px; overflow: auto; height: 70vh; min-height: 550px; max-height: 700px; background: #525659; cursor: grab; position: relative;">';
            reviewHtml += '<canvas id="review-pdf-canvas" style="display: block; margin: 20px auto;"></canvas>';
            reviewHtml += '</div>';
            
            reviewHtml += '<div style="margin-top: 20px; text-align: center;">';
            reviewHtml += '<button type="button" id="edit-info" class="btn btn-secondary" style="margin-right: 15px;">← Edit Information</button>';
            reviewHtml += '<button type="button" id="proceed-to-sign" class="btn btn-primary btn-large">✍️ Proceed to Sign</button>';
            reviewHtml += '</div>';
            reviewHtml += '</div>';

            $('#signature-overlay').html(reviewHtml).fadeIn();
            
            // Add "Powered by" branding if applicable (Free version with setting enabled)
            if (swpdfSignature.showBranding) {
                $('#signature-overlay > div').append(
                    '<div class="psf-powered-by" style="margin-top: 15px; text-align: center;">' +
                    '<a href="https://signwpdf.com" target="_blank" rel="noopener" style="font-size: 12px; color: #999; text-decoration: none;">Powered by PDF Sign & Fill</a>' +
                    '</div>'
                );
            }
            
            // Render PDF to canvas with zoom/drag
            await initReviewPdfViewer(pdfData);

            // Bind buttons
            $('#edit-info').on('click', function() {
                $('#signature-overlay').fadeOut();
                currentFieldIndex = 0;
                showFieldInput(0);
            });

            $('#proceed-to-sign').on('click', function() {
                showSignaturePad();
            });
        } catch (error) {
            console.error('Error generating preview:', error);
            showMessage('Error generating preview: ' + error.message, 'error');
        }
    }
    
    /**
     * Initialize Review PDF Viewer with Zoom and Drag
     */
    let reviewPdfDoc = null;
    let reviewPdfZoom = 1.0;
    let reviewCurrentPage = 1;
    let reviewTotalPages = 1;
    let reviewIsDragging = false;
    let reviewDragStartX, reviewDragStartY, reviewScrollStartX, reviewScrollStartY;
    
    async function initReviewPdfViewer(pdfDataUrl) {
        try {
            // Convert data URL to array buffer
            const base64 = pdfDataUrl.split(',')[1];
            const binaryString = atob(base64);
            const bytes = new Uint8Array(binaryString.length);
            for (let i = 0; i < binaryString.length; i++) {
                bytes[i] = binaryString.charCodeAt(i);
            }
            
            // Load PDF
            reviewPdfDoc = await pdfjsLib.getDocument({ data: bytes }).promise;
            reviewTotalPages = reviewPdfDoc.numPages;
            reviewCurrentPage = 1;
            
            // Show page controls if multi-page
            if (reviewTotalPages > 1) {
                $('#review-page-controls').show();
                updateReviewPageInfo();
            } else {
                $('#review-page-controls').hide();
            }
            
            // Calculate initial zoom to fit page in container
            const page = await reviewPdfDoc.getPage(1);
            const container = $('#review-pdf-container');
            const containerWidth = container.width() - 40;
            
            const defaultViewport = page.getViewport({ scale: 1.0 });
            const scaleToFitWidth = containerWidth / defaultViewport.width;
            
            reviewPdfZoom = Math.min(scaleToFitWidth / 1.5, 1.0);
            if (reviewPdfZoom < 0.5) reviewPdfZoom = 0.5;
            
            $('#review-zoom-level').text(Math.round(reviewPdfZoom * 100) + '%');
            
            // Render first page
            await renderReviewPdfPage();
            
            // Bind zoom controls
            $('#review-zoom-in').off('click').on('click', function() {
                reviewPdfZoom = Math.min(reviewPdfZoom + 0.25, 3.0);
                $('#review-zoom-level').text(Math.round(reviewPdfZoom * 100) + '%');
                renderReviewPdfPage();
            });
            
            $('#review-zoom-out').off('click').on('click', function() {
                reviewPdfZoom = Math.max(reviewPdfZoom - 0.25, 0.25);
                $('#review-zoom-level').text(Math.round(reviewPdfZoom * 100) + '%');
                renderReviewPdfPage();
            });
            
            $('#review-zoom-fit').off('click').on('click', function() {
                reviewPdfZoom = 1.0;
                $('#review-zoom-level').text('100%');
                renderReviewPdfPage();
            });
            
            // Bind page navigation
            $('#review-prev-page').off('click').on('click', function() {
                if (reviewCurrentPage > 1) {
                    reviewCurrentPage--;
                    updateReviewPageInfo();
                    renderReviewPdfPage();
                    $('#review-pdf-container').scrollTop(0);
                }
            });
            
            $('#review-next-page').off('click').on('click', function() {
                if (reviewCurrentPage < reviewTotalPages) {
                    reviewCurrentPage++;
                    updateReviewPageInfo();
                    renderReviewPdfPage();
                    $('#review-pdf-container').scrollTop(0);
                }
            });
            
            // Bind drag to pan
            const cont = $('#review-pdf-container');
            
            cont.off('mousedown').on('mousedown', function(e) {
                reviewIsDragging = true;
                reviewDragStartX = e.clientX;
                reviewDragStartY = e.clientY;
                reviewScrollStartX = cont.scrollLeft();
                reviewScrollStartY = cont.scrollTop();
                cont.css('cursor', 'grabbing');
                e.preventDefault();
            });
            
            $(document).off('mousemove.reviewDrag').on('mousemove.reviewDrag', function(e) {
                if (reviewIsDragging) {
                    const dx = e.clientX - reviewDragStartX;
                    const dy = e.clientY - reviewDragStartY;
                    cont.scrollLeft(reviewScrollStartX - dx);
                    cont.scrollTop(reviewScrollStartY - dy);
                }
            });
            
            $(document).off('mouseup.reviewDrag').on('mouseup.reviewDrag', function() {
                if (reviewIsDragging) {
                    reviewIsDragging = false;
                    cont.css('cursor', 'grab');
                }
            });
            
        } catch (error) {
            console.error('Error loading review PDF:', error);
        }
    }
    
    function updateReviewPageInfo() {
        $('#review-page-info').text('Page ' + reviewCurrentPage + ' of ' + reviewTotalPages);
        $('#review-prev-page').prop('disabled', reviewCurrentPage <= 1);
        $('#review-next-page').prop('disabled', reviewCurrentPage >= reviewTotalPages);
    }
    
    async function renderReviewPdfPage() {
        if (!reviewPdfDoc) return;
        
        const page = await reviewPdfDoc.getPage(reviewCurrentPage);
        const canvas = document.getElementById('review-pdf-canvas');
        const context = canvas.getContext('2d');
        
        const viewport = page.getViewport({ scale: 1.5 * reviewPdfZoom });
        canvas.width = viewport.width;
        canvas.height = viewport.height;
        
        await page.render({
            canvasContext: context,
            viewport: viewport
        }).promise;
    }
    
    /**
     * Show Signature Pad
     */
    function showSignaturePad() {
        let signHtml = '<div class="signature-modal">';
        signHtml += '<h3>✍️ Sign the Agreement</h3>';
        signHtml += '<p>Please sign in the box below to complete:</p>';
        signHtml += '<div class="signature-pad-wrapper">';
        signHtml += '<canvas id="signature-canvas" width="600" height="200"></canvas>';
        signHtml += '</div>';
        signHtml += '<div class="signature-actions">';
        signHtml += '<button type="button" id="clear-signature" class="btn btn-secondary">Clear</button>';
        signHtml += '<button type="button" id="preview-signed-pdf" class="btn btn-success btn-large">✓ Preview Signed Document</button>';
        signHtml += '</div>';
        signHtml += '</div>';
        
        $('#signature-overlay').html(signHtml);
        
        // Re-initialize signature pad
        initSignaturePad();
        
        // Re-bind clear button
        $('#clear-signature').on('click', function() {
            signaturePad.clear();
        });
        
        // Re-bind preview button
        $('#preview-signed-pdf').on('click', async function() {
            if (signaturePad.isEmpty()) {
                showMessage('Please provide a signature', 'error');
                return;
            }
            
            const signatureData = signaturePad.toDataURL('image/png');
            await showSignedPreview(formData, signatureData);
        });
    }
    
    /**
     * Initialize Signature Pad
     */
    function initSignaturePad() {
        const canvas = document.getElementById('signature-canvas');
        if (!canvas) return;
        
        signaturePad = new SignaturePad(canvas, {
            backgroundColor: 'rgb(255, 255, 255)',
            penColor: 'rgb(0, 0, 0)',
            minWidth: 0.5,
            maxWidth: 2.5
        });
        
        resizeCanvas(canvas);
    }
    
    /**
     * Resize Canvas
     */
    function resizeCanvas(canvas) {
        if (!canvas) return;
        const ratio = Math.max(window.devicePixelRatio || 1, 1);
        canvas.width = canvas.offsetWidth * ratio;
        canvas.height = canvas.offsetHeight * ratio;
        canvas.getContext('2d').scale(ratio, ratio);
    }

    /**
     * Generate Filled PDF Preview (no signature)
     * Shows: form fields + date + manual fields
     */
    async function generateFilledPDFPreview(data) {
        try {
            if (!pdfTemplate || !pdfTemplate.filename) {
                throw new Error('PDF template not loaded');
            }

            // Add cache-busting to ensure fresh PDF is loaded
            const cacheBuster = '?v=' + Date.now();
            const templateUrl = swpdfSignature.templatesUrl + pdfTemplate.filename + cacheBuster;
            const existingPdfBytes = await fetch(templateUrl).then(res => res.arrayBuffer());

            if (typeof PDFLib === 'undefined') {
                throw new Error('PDF-lib library not loaded');
            }

            const { PDFDocument, StandardFonts, rgb } = PDFLib;
            const pdfDoc = await PDFDocument.load(existingPdfBytes);
            
            // Embed font for manual fields
            const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica);
            
            // Get saved fields list to identify manual fields
            const savedFields = window.savedFieldsList || [];
            const manualFieldsMap = {};
            savedFields.forEach(function(f) {
                if (f.isManual && f.position) {
                    manualFieldsMap[f.name] = f;
                }
            });

            // Fill form fields with consistent font size
            const form = pdfDoc.getForm();
            
            // Get today's date in MM/DD/YY format
            const today = new Date();
            const month = String(today.getMonth() + 1).padStart(2, '0');
            const day = String(today.getDate()).padStart(2, '0');
            const year = String(today.getFullYear()).slice(-2);
            const dateStr = month + '/' + day + '/' + year;
            
            // Date field names to skip in general fill loop
            const dateFieldNamesLower = ['date', 'date_', 'signaturedate', 'signature_date', 'date_2', 'today', 'currentdate', 'current_date'];
            
            Object.entries(data).forEach(([fieldName, value]) => {
                // Skip manual fields - drawn separately
                if (manualFieldsMap[fieldName]) {
                    return;
                }
                // Skip date fields - handled separately
                const fieldNameLower = fieldName.toLowerCase();
                if (dateFieldNamesLower.some(df => fieldNameLower === df || fieldNameLower.includes('date'))) {
                    return;
                }
                try {
                    const field = form.getTextField(fieldName);
                    field.setFontSize(12);
                    field.setText(String(value));
                } catch (e) {
                    // ignore missing fields
                }
            });
            
            // Fill only the FIRST date field; REMOVE every other date field entirely
            let previewDateFilled = false;
            const dateFieldsToRemove = [];
            try {
                const allFields = form.getFields();
                for (let fi = 0; fi < allFields.length; fi++) {
                    const name = allFields[fi].getName();
                    const nameLower = name.toLowerCase();
                    if (nameLower.includes('date') || nameLower === 'today' || nameLower === 'currentdate') {
                        if (!previewDateFilled) {
                            try {
                                const textField = form.getTextField(name);
                                textField.setFontSize(12);
                                textField.setText(dateStr);
                                previewDateFilled = true;
                            } catch (e) {
                                // Not a text field — remove it too
                                dateFieldsToRemove.push(name);
                            }
                        } else {
                            // Mark subsequent date fields for removal
                            dateFieldsToRemove.push(name);
                        }
                    }
                }
            } catch (e) {
                // Fallback: could not enumerate fields
            }
            // Remove duplicate date fields BEFORE flattening
            dateFieldsToRemove.forEach(function(name) {
                try { form.removeField(form.getField(name)); } catch (e) {}
            });

            // Flatten form
            form.flatten();
            
            // Draw manual fields on their respective pages
            const pages = pdfDoc.getPages();
            Object.entries(data).forEach(([fieldName, value]) => {
                if (manualFieldsMap[fieldName] && value) {
                    const mf = manualFieldsMap[fieldName];
                    const pageIndex = (mf.page || 1) - 1;
                    if (pages[pageIndex]) {
                        const page = pages[pageIndex];
                        const { height: pageHeight } = page.getSize();
                        const fontSize = Math.min(12, Math.max(8, (mf.position.height || 20) * 0.6));
                        const pdfY = pageHeight - (mf.position.y || 400) - (mf.position.height || 20);
                        
                        page.drawText(String(value), {
                            x: mf.position.x || 100,
                            y: pdfY,
                            size: fontSize,
                            font: helveticaFont,
                            color: rgb(0, 0, 0)
                        });
                    }
                }
            });

            const pdfBytes = await pdfDoc.save();
            const pdfBlob = new Blob([pdfBytes], { type: 'application/pdf' });

            const reader = new FileReader();
            return new Promise((resolve) => {
                reader.readAsDataURL(pdfBlob);
                reader.onloadend = function() {
                    resolve(reader.result);
                };
            });
        } catch (error) {
            console.error('Error generating preview PDF:', error);
            showMessage('Error generating preview: ' + error.message, 'error');
            return null;
        }
    }
    
    /**
     * Show Signed PDF Preview
     */
    async function showSignedPreview(data, signatureData) {
        try {
            showMessage('Generating preview...', 'info');
            
            // Generate the PDF
            const pdfData = await generateFilledPDF(data, signatureData, true);
            
            if (!pdfData) {
                return;
            }
            
            // Store for rendering
            window.signedPdfData = pdfData;
            
            // Show preview with zoom controls and draggable document
            let previewHtml = '<div style="max-width: 950px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px;">';
            previewHtml += '<h2 style="margin-top: 0; text-align: center;">✅ Your Signed Document</h2>';
            
            // Zoom controls and page navigation
            previewHtml += '<div style="text-align: center; margin-bottom: 15px; padding: 10px; background: #f5f5f5; border-radius: 6px;">';
            previewHtml += '<span style="font-weight: 600; margin-right: 15px;">🔍 ZOOM:</span>';
            previewHtml += '<button type="button" id="zoom-out" class="btn btn-secondary btn-small" style="padding: 5px 15px; margin: 0 5px;">−</button>';
            previewHtml += '<span id="zoom-level" style="display: inline-block; min-width: 60px; text-align: center; font-weight: bold;">100%</span>';
            previewHtml += '<button type="button" id="zoom-in" class="btn btn-secondary btn-small" style="padding: 5px 15px; margin: 0 5px;">+</button>';
            previewHtml += '<button type="button" id="zoom-fit" class="btn btn-secondary btn-small" style="padding: 5px 15px; margin-left: 15px;">Fit</button>';
            previewHtml += '<span style="margin-left: 30px; border-left: 1px solid #ccc; padding-left: 20px;">';
            previewHtml += '<button type="button" id="preview-prev-page" class="btn btn-secondary btn-small" style="padding: 5px 12px;">◀</button>';
            previewHtml += '<span id="preview-page-info" style="display: inline-block; min-width: 90px; text-align: center; font-weight: bold;">Page 1 of 1</span>';
            previewHtml += '<button type="button" id="preview-next-page" class="btn btn-secondary btn-small" style="padding: 5px 12px;">▶</button>';
            previewHtml += '</span>';
            previewHtml += '</div>';
            
            // PDF viewer container with canvas - scrollable to see full document
            previewHtml += '<div id="pdf-preview-container" style="margin: 15px 0; border: 2px solid #ddd; border-radius: 4px; overflow: auto; height: 70vh; min-height: 550px; max-height: 700px; background: #525659; cursor: grab; position: relative;">';
            previewHtml += '<canvas id="signed-pdf-canvas" style="display: block; margin: 20px auto;"></canvas>';
            previewHtml += '</div>';
            
            previewHtml += '<div style="margin-top: 20px; text-align: center;">';
            previewHtml += '<button type="button" id="go-back-edit" class="btn btn-secondary" style="margin-right: 15px;">← Re-sign</button>';
            previewHtml += '<button type="button" id="final-submit" class="btn btn-success btn-large">📤 Submit Agreement</button>';
            previewHtml += '</div>';
            previewHtml += '</div>';
            
            $('#signature-overlay').html(previewHtml).fadeIn();
            
            // Render PDF to canvas with zoom/drag
            await initSignedPdfViewer(pdfData);
            
            // Bind buttons
            $('#go-back-edit').on('click', function() {
                // Go back to signature pad, not all the way to field input
                showSignaturePad();
            });
            
            $('#final-submit').on('click', function() {
                submitToServer(data, signatureData, pdfData);
            });
            
        } catch (error) {
            console.error('Error generating preview:', error);
            showMessage('Error generating preview: ' + error.message, 'error');
        }
    }
    
    /**
     * Generate Filled PDF
     */
    async function generateFilledPDF(data, signatureData, returnDataUrl = false) {
        try {
            showMessage('Generating PDF...', 'info');
            
            if (!pdfTemplate || !pdfTemplate.filename) {
                throw new Error('PDF template not loaded');
            }
            
            // Add cache-busting to ensure fresh PDF is loaded
            const cacheBuster = '?v=' + Date.now();
            const templateUrl = swpdfSignature.templatesUrl + pdfTemplate.filename + cacheBuster;
            const existingPdfBytes = await fetch(templateUrl).then(res => res.arrayBuffer());
            
            if (typeof PDFLib === 'undefined') {
                throw new Error('PDF-lib library not loaded');
            }
            
            const { PDFDocument, StandardFonts, rgb } = PDFLib;
            const pdfDoc = await PDFDocument.load(existingPdfBytes);
            
            // Embed font for manual fields
            const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica);
            
            // Get saved fields list to identify manual fields
            const savedFields = window.savedFieldsList || [];
            const manualFieldsMap = {};
            savedFields.forEach(function(f) {
                if (f.isManual && f.position) {
                    manualFieldsMap[f.name] = f;
                }
            });
            
            // Fill form fields
            const form = pdfDoc.getForm();
            
            // Get today's date in MM/DD/YY format
            const today = new Date();
            const month = String(today.getMonth() + 1).padStart(2, '0');
            const day = String(today.getDate()).padStart(2, '0');
            const year = String(today.getFullYear()).slice(-2);
            const dateStr = month + '/' + day + '/' + year;
            
            // Date field names to skip in general fill loop (handled separately below)
            const dateFieldNamesLower = ['date', 'date_', 'signaturedate', 'signature_date', 'date_2', 'today', 'currentdate', 'current_date'];
            
            Object.entries(data).forEach(([fieldName, value]) => {
                // Check if this is a manual field
                if (manualFieldsMap[fieldName]) {
                    // Will be drawn directly on page later
                    return;
                }
                
                // Skip date fields - they are auto-filled separately below
                const fieldNameLower = fieldName.toLowerCase();
                if (dateFieldNamesLower.some(df => fieldNameLower === df || fieldNameLower.includes('date'))) {
                    swpdfLog(`Skipping date field in general fill: ${fieldName}`);
                    return;
                }
                
                try {
                    const field = form.getTextField(fieldName);
                    // Set consistent font size (12pt) for all text fields
                    field.setFontSize(12);
                    field.setText(String(value));
                    swpdfLog(`Filled: ${fieldName} = ${value}`);
                } catch (e) {
                    swpdfLog(`Field ${fieldName} not found`);
                }
            });
            
            // Fill only the FIRST date field; REMOVE every other date field entirely
            let dateFieldFound = false;
            let dateFieldFilledOnce = false;
            const signedDateFieldsToRemove = [];
            try {
                const allFields = form.getFields();
                for (let fi = 0; fi < allFields.length; fi++) {
                    const name = allFields[fi].getName();
                    const nameLower = name.toLowerCase();
                    if (nameLower.includes('date') || nameLower === 'today' || nameLower === 'currentdate') {
                        dateFieldFound = true;
                        if (!dateFieldFilledOnce) {
                            try {
                                const textField = form.getTextField(name);
                                textField.setFontSize(12);
                                textField.setText(dateStr);
                                dateFieldFilledOnce = true;
                                swpdfLog('Filled date field: ' + name + ' = ' + dateStr);
                            } catch (fillErr) {
                                swpdfLog('Date field not a text field, removing: ' + name);
                                signedDateFieldsToRemove.push(name);
                            }
                        } else {
                            // Mark subsequent date fields for complete removal
                            signedDateFieldsToRemove.push(name);
                            swpdfLog('Marked duplicate date field for removal: ' + name);
                        }
                    }
                }
            } catch (e) {
                swpdfLog('Could not enumerate form fields: ' + e.message);
            }
            // Remove duplicate date fields BEFORE flattening
            signedDateFieldsToRemove.forEach(function(name) {
                try {
                    form.removeField(form.getField(name));
                    swpdfLog('Removed duplicate date field: ' + name);
                } catch (e) {
                    swpdfLog('Could not remove field: ' + name);
                }
            });
            
            // Get signature position from admin settings or use defaults
            const sigSettings = window.signatureSettings || {};
            let signatureX = sigSettings.x || 72;
            let signatureY = sigSettings.y || 68;
            let maxSigWidth = sigSettings.width || 120;
            let maxSigHeight = sigSettings.height || 35;
            let signaturePage = sigSettings.page || 0; // 0 means last page
            
            swpdfLog('Using signature settings:', { x: signatureX, y: signatureY, width: maxSigWidth, height: maxSigHeight, page: signaturePage });
            
            // Flatten form
            form.flatten();
            
            // Draw manual fields on their respective pages
            const pages = pdfDoc.getPages();
            Object.entries(data).forEach(([fieldName, value]) => {
                if (manualFieldsMap[fieldName] && value) {
                    const mf = manualFieldsMap[fieldName];
                    const pageIndex = (mf.page || 1) - 1; // Convert 1-based to 0-based
                    if (pages[pageIndex]) {
                        const page = pages[pageIndex];
                        const { width: pageWidth, height: pageHeight } = page.getSize();
                        
                        // Calculate font size to fit the field height (approximately)
                        const fontSize = Math.min(12, Math.max(8, (mf.position.height || 20) * 0.6));
                        
                        // Convert Y coordinate: admin stores Y from top, PDF-lib uses Y from bottom
                        // The position.y stored is the TOP of the field box, so we need to convert
                        const pdfY = pageHeight - (mf.position.y || 400) - (mf.position.height || 20);
                        
                        page.drawText(String(value), {
                            x: mf.position.x || 100,
                            y: pdfY,
                            size: fontSize,
                            font: helveticaFont,
                            color: rgb(0, 0, 0)
                        });
                        swpdfLog('Drew manual field:', fieldName, 'at x:', mf.position.x, 'y (converted):', pdfY, 'value:', value);
                    }
                }
            });
            
            // Add signature image at the configured position
            // Determine which page to put the signature on
            // (pages already defined above)
            let targetPage;
            if (signaturePage > 0 && signaturePage <= pages.length) {
                // Use configured page (1-based, so subtract 1 for index)
                targetPage = pages[signaturePage - 1];
            } else {
                // Default to last page
                targetPage = pages[pages.length - 1];
            }
            
            const signatureImage = await pdfDoc.embedPng(signatureData);
            
            // Scale signature to fit within max dimensions from settings
            const scaleFactor = Math.min(maxSigWidth / signatureImage.width, maxSigHeight / signatureImage.height);
            const scaledWidth = signatureImage.width * scaleFactor;
            const scaledHeight = signatureImage.height * scaleFactor;
            
            swpdfLog('Drawing signature at:', { x: signatureX, y: signatureY, width: scaledWidth, height: scaledHeight, page: signaturePage || 'last' });
            
            targetPage.drawImage(signatureImage, {
                x: signatureX,
                y: signatureY,
                width: scaledWidth,
                height: scaledHeight
            });
            
            // Manual date stamp: ONLY draw if enabled AND the PDF had NO date form fields at all
            // If the PDF already has a date field (even one we filled), skip the manual stamp entirely
            const dateSettings = window.dateSettings || {};
            if (dateSettings.enabled && !dateFieldFound) {
                const dateX = dateSettings.x || 350;
                const dateY = dateSettings.y || 68;
                const dateFontSize = dateSettings.fontSize || 10;
                const datePage = dateSettings.page || 0;
                
                let dateTargetPage;
                if (datePage > 0 && datePage <= pages.length) {
                    dateTargetPage = pages[datePage - 1];
                } else {
                    dateTargetPage = targetPage;
                }
                
                swpdfLog('Drawing manual date stamp at:', { x: dateX, y: dateY, fontSize: dateFontSize });
                
                dateTargetPage.drawText(dateStr, {
                    x: dateX,
                    y: dateY,
                    size: dateFontSize,
                    font: helveticaFont,
                    color: rgb(0, 0, 0)
                });
            } else {
                swpdfLog('Manual date stamp skipped — dateFieldFound=' + dateFieldFound + ', dateSettings.enabled=' + dateSettings.enabled);
            }
            
            // Save PDF
            const pdfBytes = await pdfDoc.save();
            const pdfBlob = new Blob([pdfBytes], { type: 'application/pdf' });
            
            // If preview mode, return data URL for iframe
            if (returnDataUrl) {
                const reader = new FileReader();
                return new Promise((resolve) => {
                    reader.readAsDataURL(pdfBlob);
                    reader.onloadend = function() {
                        resolve(reader.result);
                    };
                });
            }
            
            // Otherwise convert to base64 for submission
            const reader = new FileReader();
            reader.readAsDataURL(pdfBlob);
            reader.onloadend = function() {
                submitToServer(data, signatureData, reader.result);
            };
            
        } catch (error) {
            console.error('Error generating PDF:', error);
            showMessage('Error generating PDF: ' + error.message, 'error');
            return null;
        }
    }
    
    /**
     * Submit to Server
     */
    function submitToServer(formData, signatureData, pdfData) {
        // Disable submit button
        $('#final-submit').prop('disabled', true).text('Submitting...');
        
        // If we collected email from gate, ensure it's in form data
        if (gatedEmail && !formData.customer_email && !formData.email) {
            formData.customer_email = gatedEmail;
        }
        
        $.ajax({
            url: swpdfSignature.ajaxUrl,
            type: 'POST',
            data: {
                action: 'swpdf_save_signed_pdf',
                nonce: swpdfSignature.nonce,
                form_data: JSON.stringify(formData),
                signature_data: signatureData,
                pdf_data: pdfData,
                agreement_type: $('#psf-signature-form').data('agreement-type')
            },
            success: function(response) {
                if (response.success) {
                    showThankYouMessage(response.data);
                } else {
                    showMessage(response.data.message || 'Submission failed', 'error');
                    $('#final-submit').prop('disabled', false).text('📤 Submit Agreement');
                }
            },
            error: function() {
                showMessage('Error submitting agreement', 'error');
                $('#final-submit').prop('disabled', false).text('📤 Submit Agreement');
            }
        });
    }
    
    /**
     * Show Thank You Message
     */
    function showThankYouMessage(data) {
        const title = data.success_title || 'Thank You!';
        const message = data.success_message || 'Your document has been signed successfully.';
        const downloadUrl = data.download_url || '';
        const redirectUrl = data.redirect_url || '';
        const redirectDelay = data.redirect_delay || 5;
        const allowDownload = data.allow_download;
        
        let thankYouHtml = '<div style="max-width: 700px; margin: 0 auto; background: white; padding: 50px; border-radius: 8px; text-align: center;">';
        thankYouHtml += '<div style="font-size: 64px; margin-bottom: 20px;">✅</div>';
        thankYouHtml += '<h2 style="color: #28a745; margin-top: 0;">' + escapeHtml(title) + '</h2>';
        thankYouHtml += '<p style="font-size: 18px; color: #666; line-height: 1.6;">' + escapeHtml(message) + '</p>';
        
        // Download button (if allowed)
        if (allowDownload && downloadUrl) {
            thankYouHtml += '<div style="margin: 30px 0;">';
            thankYouHtml += '<a href="' + downloadUrl + '" download class="btn btn-success btn-large" style="display: inline-block; padding: 15px 30px; background: #28a745; color: white; text-decoration: none; border-radius: 5px; font-size: 16px;">📥 Download Your Signed Document</a>';
            thankYouHtml += '</div>';
        }
        
        // Additional info section - only show if provided in settings
        const additionalInfo = data.success_additional_info || '';
        if (additionalInfo && additionalInfo.trim() !== '') {
            thankYouHtml += '<div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 30px 0;">';
            thankYouHtml += '<div style="text-align: left;">' + additionalInfo + '</div>';
            thankYouHtml += '</div>';
        }
        
        // Redirect notice
        if (redirectUrl) {
            thankYouHtml += '<p style="color: #666; font-size: 14px;" id="redirect-notice">Redirecting in <span id="countdown">' + redirectDelay + '</span> seconds...</p>';
        }
        
        thankYouHtml += '<button type="button" id="close-thank-you" class="btn btn-primary btn-large" style="margin-top: 20px;">' + (redirectUrl ? 'Continue Now' : 'Close') + '</button>';
        thankYouHtml += '</div>';
        
        $('#signature-overlay').html(thankYouHtml).fadeIn();
        
        // Hide the form section
        $('.pdf-interactive-section').fadeOut();
        
        // Handle redirect
        if (redirectUrl) {
            let countdown = redirectDelay;
            const countdownInterval = setInterval(function() {
                countdown--;
                $('#countdown').text(countdown);
                if (countdown <= 0) {
                    clearInterval(countdownInterval);
                    window.location.href = redirectUrl;
                }
            }, 1000);
            
            // Continue button stops countdown and redirects immediately
            $('#close-thank-you').on('click', function() {
                clearInterval(countdownInterval);
                window.location.href = redirectUrl;
            });
        } else {
            // No redirect - just close/go home
            $('#close-thank-you').on('click', function() {
                window.location.href = '/';
            });
        }
    }
    
    /**
     * Escape HTML to prevent XSS
     */
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    /**
     * Show Message
     */
    function showMessage(message, type) {
        const messageDiv = $('<div>')
            .addClass('alert alert-' + type)
            .text(message)
            .appendTo('#message-container');
        
        setTimeout(function() {
            messageDiv.fadeOut(function() {
                $(this).remove();
            });
        }, 5000);
    }
    
    /**
     * Initialize Signed PDF Viewer with Zoom and Drag
     */
    let signedPdfDoc = null;
    let signedPdfZoom = 1.0;
    let signedPdfCurrentPage = 1;
    let signedPdfTotalPages = 1;
    let isDragging = false;
    let dragStartX, dragStartY, scrollStartX, scrollStartY;
    
    async function initSignedPdfViewer(pdfDataUrl) {
        try {
            // Convert data URL to array buffer
            const base64 = pdfDataUrl.split(',')[1];
            const binaryString = atob(base64);
            const bytes = new Uint8Array(binaryString.length);
            for (let i = 0; i < binaryString.length; i++) {
                bytes[i] = binaryString.charCodeAt(i);
            }
            
            // Load PDF
            signedPdfDoc = await pdfjsLib.getDocument({ data: bytes }).promise;
            signedPdfTotalPages = signedPdfDoc.numPages;
            signedPdfCurrentPage = 1;
            
            // Update page info
            $('#preview-page-info').text('Page ' + signedPdfCurrentPage + ' of ' + signedPdfTotalPages);
            $('#preview-prev-page').prop('disabled', true);
            $('#preview-next-page').prop('disabled', signedPdfTotalPages <= 1);
            
            // Calculate initial zoom to fit page in container
            const page = await signedPdfDoc.getPage(1);
            const container = $('#pdf-preview-container');
            const containerWidth = container.width() - 40; // padding
            const containerHeight = container.height() - 20;
            
            const defaultViewport = page.getViewport({ scale: 1.0 });
            const scaleToFitWidth = containerWidth / defaultViewport.width;
            const scaleToFitHeight = containerHeight / defaultViewport.height;
            
            // Start with fit-to-width scale (so full width is visible)
            signedPdfZoom = Math.min(scaleToFitWidth / 1.5, 1.0); // Divide by 1.5 because render uses 1.5 * zoom
            if (signedPdfZoom < 0.5) signedPdfZoom = 0.5;
            
            $('#zoom-level').text(Math.round(signedPdfZoom * 100) + '%');
            
            // Render first page
            await renderSignedPdfPage();
            
            // Bind zoom controls
            $('#zoom-in').off('click').on('click', function() {
                signedPdfZoom = Math.min(signedPdfZoom + 0.25, 3.0);
                $('#zoom-level').text(Math.round(signedPdfZoom * 100) + '%');
                renderSignedPdfPage();
            });
            
            $('#zoom-out').off('click').on('click', function() {
                signedPdfZoom = Math.max(signedPdfZoom - 0.25, 0.25);
                $('#zoom-level').text(Math.round(signedPdfZoom * 100) + '%');
                renderSignedPdfPage();
            });
            
            $('#zoom-fit').off('click').on('click', function() {
                signedPdfZoom = 1.0;
                $('#zoom-level').text('100%');
                renderSignedPdfPage();
            });
            
            // Bind page navigation
            $('#preview-prev-page').off('click').on('click', function() {
                if (signedPdfCurrentPage > 1) {
                    signedPdfCurrentPage--;
                    $('#preview-page-info').text('Page ' + signedPdfCurrentPage + ' of ' + signedPdfTotalPages);
                    $('#preview-prev-page').prop('disabled', signedPdfCurrentPage <= 1);
                    $('#preview-next-page').prop('disabled', false);
                    renderSignedPdfPage();
                }
            });
            
            $('#preview-next-page').off('click').on('click', function() {
                if (signedPdfCurrentPage < signedPdfTotalPages) {
                    signedPdfCurrentPage++;
                    $('#preview-page-info').text('Page ' + signedPdfCurrentPage + ' of ' + signedPdfTotalPages);
                    $('#preview-prev-page').prop('disabled', false);
                    $('#preview-next-page').prop('disabled', signedPdfCurrentPage >= signedPdfTotalPages);
                    renderSignedPdfPage();
                }
            });
            
            // Bind drag to pan
            const cont = $('#pdf-preview-container');
            
            cont.off('mousedown').on('mousedown', function(e) {
                isDragging = true;
                dragStartX = e.clientX;
                dragStartY = e.clientY;
                scrollStartX = cont.scrollLeft();
                scrollStartY = cont.scrollTop();
                cont.css('cursor', 'grabbing');
                e.preventDefault();
            });
            
            $(document).off('mousemove.pdfDrag').on('mousemove.pdfDrag', function(e) {
                if (isDragging) {
                    const dx = e.clientX - dragStartX;
                    const dy = e.clientY - dragStartY;
                    cont.scrollLeft(scrollStartX - dx);
                    cont.scrollTop(scrollStartY - dy);
                }
            });
            
            $(document).off('mouseup.pdfDrag').on('mouseup.pdfDrag', function() {
                if (isDragging) {
                    isDragging = false;
                    cont.css('cursor', 'grab');
                }
            });
            
        } catch (error) {
            console.error('Error loading signed PDF:', error);
        }
    }
    
    async function renderSignedPdfPage() {
        if (!signedPdfDoc) return;
        
        const page = await signedPdfDoc.getPage(signedPdfCurrentPage);
        const canvas = document.getElementById('signed-pdf-canvas');
        const context = canvas.getContext('2d');
        
        const viewport = page.getViewport({ scale: 1.5 * signedPdfZoom });
        canvas.width = viewport.width;
        canvas.height = viewport.height;
        
        await page.render({
            canvasContext: context,
            viewport: viewport
        }).promise;
        
        // Update cursor based on zoom
        $('#pdf-preview-container').css('cursor', signedPdfZoom > 1.0 ? 'grab' : 'default');
    }
    
    /**
     * Bind Events
     */
    function bindEvents() {
        // Page navigation
        $('#prev-page').on('click', function() {
            if (currentPage > 1) {
                renderPage(currentPage - 1);
                renderFieldOverlays();
            }
        });
        
        $('#next-page').on('click', function() {
            if (currentPage < totalPages) {
                renderPage(currentPage + 1);
                renderFieldOverlays();
            }
        });
    }
    
    // Initialize on load
    init();
});


