jQuery(document).ready(function($) {
    
    // Global variables
    let countdownTimer;
    let currentMobile = '';
    
    // Initialize forms
    initForms();
    
    function initForms() {
        // Mobile form submission
        $(document).on('submit', '.dga-mobile-form', function(e) {
            e.preventDefault();
            sendOTP($(this));
        });
        
        // OTP form submission
        $(document).on('submit', '.dga-otp-form', function(e) {
            e.preventDefault();
            verifyOTP($(this));
        });
        
        // Registration form submission
        $(document).on('submit', '.dga-register-form', function(e) {
            e.preventDefault();
            completeRegistration($(this));
        });
        
        // Back button clicks
        $(document).on('click', '.dga-back-btn', function() {
            goToPreviousStep($(this));
        });
        
        // OTP input formatting
        $(document).on('input', '#otp', function() {
            formatOTPInput($(this));
        });
        
        // Mobile input formatting
        $(document).on('input', '#mobile', function() {
            formatMobileInput($(this));
        });
    }
    
    /**
     * Send OTP to mobile number
     */
    function sendOTP(form) {
        const mobile = form.find('#mobile').val().trim();
        
        if (!mobile) {
            showMessage('Please enter a mobile number.', 'error');
            return;
        }
        
        // Validate mobile format
        if (!/^09[0-9]{9}$/.test(mobile)) {
            showMessage('Please enter a valid mobile number (09xxxxxxxxx).', 'error');
            return;
        }
        
        const submitBtn = form.find('button[type="submit"]');
        const originalText = submitBtn.text();
        
        // Disable button and show loading
        submitBtn.prop('disabled', true).text(dga_ajax.strings.sending_otp);
        
        // Send AJAX request
        $.ajax({
            url: dga_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'dga_send_otp',
                mobile: mobile,
                nonce: dga_ajax.nonce
            },
            success: function(response) {
                try {
                    const data = JSON.parse(response);
                    
                    if (data.success) {
                        currentMobile = mobile;
                        showMessage(data.message, 'success');
                        
                        // Move to OTP step
                        const container = form.closest('.dga-step').parent();
                        goToStep(container, 2);
                        
                        // Start countdown
                        startCountdown();
                        
                        // Set mobile in hidden field
                        container.find('#otp-mobile').val(mobile);
                        
                    } else {
                        showMessage(data.message, 'error');
                    }
                } catch (e) {
                    showMessage('An error occurred. Please try again.', 'error');
                }
            },
            error: function() {
                showMessage('Network error. Please try again.', 'error');
            },
            complete: function() {
                // Re-enable button
                submitBtn.prop('disabled', false).text(originalText);
            }
        });
    }
    
    /**
     * Verify OTP code
     */
    function verifyOTP(form) {
        const mobile = form.find('#otp-mobile').val();
        const otp = form.find('#otp').val().trim();
        
        if (!otp) {
            showMessage('Please enter the OTP code.', 'error');
            return;
        }
        
        if (otp.length !== 6) {
            showMessage('Please enter a valid 6-digit OTP code.', 'error');
            return;
        }
        
        const submitBtn = form.find('button[type="submit"]');
        const originalText = submitBtn.text();
        
        // Disable button and show loading
        submitBtn.prop('disabled', true).text(dga_ajax.strings.verifying_otp);
        
        // Send AJAX request
        $.ajax({
            url: dga_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'dga_verify_otp',
                mobile: mobile,
                otp: otp,
                nonce: dga_ajax.nonce
            },
            success: function(response) {
                try {
                    const data = JSON.parse(response);
                    
                    if (data.success) {
                        showMessage(data.message, 'success');
                        
                        if (data.user_exists) {
                            // User exists, redirect
                            setTimeout(function() {
                                window.location.href = data.redirect;
                            }, 1500);
                        } else {
                            // User doesn't exist, go to registration
                            const container = form.closest('.dga-step').parent();
                            goToStep(container, 3);
                            
                            // Set mobile in hidden field
                            container.find('#reg-mobile').val(mobile);
                        }
                        
                        // Stop countdown
                        stopCountdown();
                        
                    } else {
                        showMessage(data.message, 'error');
                    }
                } catch (e) {
                    showMessage('An error occurred. Please try again.', 'error');
                }
            },
            error: function() {
                showMessage('Network error. Please try again.', 'error');
            },
            complete: function() {
                // Re-enable button
                submitBtn.prop('disabled', false).text(originalText);
            }
        });
    }
    
    /**
     * Complete user registration
     */
    function completeRegistration(form) {
        const mobile = form.find('#reg-mobile').val();
        const firstName = form.find('#first_name').val().trim();
        const lastName = form.find('#last_name').val().trim();
        const nationalCode = form.find('#national_code').val().trim();
        const birthDate = form.find('#birth_date').val();
        
        if (!firstName || !lastName || !nationalCode || !birthDate) {
            showMessage('Please fill in all required fields.', 'error');
            return;
        }
        
        // Validate national code
        if (!/^[0-9]{10}$/.test(nationalCode)) {
            showMessage('Please enter a valid 10-digit national code.', 'error');
            return;
        }
        
        const submitBtn = form.find('button[type="submit"]');
        const originalText = submitBtn.text();
        
        // Disable button and show loading
        submitBtn.prop('disabled', true).text(dga_ajax.strings.registering);
        
        // Send AJAX request
        $.ajax({
            url: dga_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'dga_complete_registration',
                mobile: mobile,
                first_name: firstName,
                last_name: lastName,
                national_code: nationalCode,
                birth_date: birthDate,
                nonce: dga_ajax.nonce
            },
            success: function(response) {
                try {
                    const data = JSON.parse(response);
                    
                    if (data.success) {
                        showMessage(data.message, 'success');
                        
                        // Redirect after successful registration
                        setTimeout(function() {
                            window.location.href = data.redirect;
                        }, 1500);
                        
                    } else {
                        showMessage(data.message, 'error');
                    }
                } catch (e) {
                    showMessage('An error occurred. Please try again.', 'error');
                }
            },
            error: function() {
                showMessage('Network error. Please try again.', 'error');
            },
            complete: function() {
                // Re-enable button
                submitBtn.prop('disabled', false).text(originalText);
            }
        });
    }
    
    /**
     * Navigate to specific step
     */
    function goToStep(container, stepNumber) {
        container.find('.dga-step').hide();
        container.find('.dga-step-' + stepNumber).show();
        
        // Clear any previous messages
        container.find('.dga-messages').empty();
    }
    
    /**
     * Go to previous step
     */
    function goToPreviousStep(button) {
        const container = button.closest('.dga-step').parent();
        const currentStep = container.find('.dga-step:visible').index() + 1;
        
        if (currentStep > 1) {
            goToStep(container, currentStep - 1);
        }
    }
    
    /**
     * Start countdown timer
     */
    function startCountdown() {
        let timeLeft = 120; // 2 minutes
        
        const countdownElement = $('#countdown');
        const resendBtn = $('.dga-resend-btn');
        
        countdownTimer = setInterval(function() {
            if (timeLeft <= 0) {
                stopCountdown();
                countdownElement.parent().html('<button type="button" class="dga-resend-btn">Resend OTP</button>');
                return;
            }
            
            countdownElement.text(timeLeft);
            timeLeft--;
        }, 1000);
    }
    
    /**
     * Stop countdown timer
     */
    function stopCountdown() {
        if (countdownTimer) {
            clearInterval(countdownTimer);
            countdownTimer = null;
        }
    }
    
    /**
     * Format OTP input
     */
    function formatOTPInput(input) {
        let value = input.val().replace(/[^0-9]/g, '');
        
        if (value.length > 6) {
            value = value.substring(0, 6);
        }
        
        input.val(value);
    }
    
    /**
     * Format mobile input
     */
    function formatMobileInput(input) {
        let value = input.val().replace(/[^0-9]/g, '');
        
        if (value.length > 11) {
            value = value.substring(0, 11);
        }
        
        input.val(value);
    }
    
    /**
     * Show message
     */
    function showMessage(message, type) {
        const messageContainer = $('.dga-messages');
        const messageClass = type === 'error' ? 'dga-error' : 'dga-success';
        
        const messageHtml = `
            <div class="dga-message ${messageClass}">
                ${message}
                <span class="dga-close-message">&times;</span>
            </div>
        `;
        
        messageContainer.html(messageHtml);
        
        // Auto-hide after 5 seconds
        setTimeout(function() {
            messageContainer.empty();
        }, 5000);
    }
    
    /**
     * Close message
     */
    $(document).on('click', '.dga-close-message', function() {
        $(this).closest('.dga-message').remove();
    });
    
    /**
     * Resend OTP functionality
     */
    $(document).on('click', '.dga-resend-btn', function() {
        if (currentMobile) {
            // Create a temporary form to resend OTP
            const tempForm = $('<form class="dga-mobile-form"><input type="hidden" id="mobile" value="' + currentMobile + '"></form>');
            sendOTP(tempForm);
        }
    });
    
    /**
     * Modal functionality
     */
    $(document).on('click', '.dga-open-modal', function(e) {
        e.preventDefault();
        const formType = $(this).data('form-type');
        openModal(formType);
    });
    
    $(document).on('click', '.dga-close', function() {
        closeModal();
    });
    
    $(document).on('click', '#dga-modal', function(e) {
        if (e.target === this) {
            closeModal();
        }
    });
    
    function openModal(formType) {
        $.ajax({
            url: dga_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'dga_get_form_html',
                form_type: formType,
                nonce: dga_ajax.nonce
            },
            success: function(response) {
                $('#dga-modal-body').html(response);
                $('#dga-modal').show();
                $('body').addClass('dga-modal-open');
            }
        });
    }
    
    function closeModal() {
        $('#dga-modal').hide();
        $('body').removeClass('dga-modal-open');
        $('#dga-modal-body').empty();
    }
    
    /**
     * Keyboard shortcuts
     */
    $(document).on('keydown', function(e) {
        // ESC key to close modal
        if (e.keyCode === 27) {
            closeModal();
        }
        
        // Enter key in OTP input
        if (e.keyCode === 13 && $(e.target).is('#otp')) {
            $(e.target).closest('form').submit();
        }
    });
    
}); 