/**
 * User Signup Block JavaScript
 */

document.addEventListener('DOMContentLoaded', function() {
    // Track page view with form
    if (typeof gtag !== 'undefined') {
        gtag('event', 'page_view', {
            page_title: document.title,
            page_location: window.location.href,
            content_group1: 'User Signup Form'
        });
    }
    
    // Custom Google Analytics tracking function
    function trackEvent(triggerName, eventCategory = 'User Signup', eventLabel = '', value = null) {
        // Find the custom event configuration
        const customEvent = window.smarter_blocks_custom_ga_events.find(event => event.name === triggerName);
        
        if (customEvent && customEvent.code) {
            try {
                // Execute the custom JavaScript code
                eval(customEvent.code);
            } catch (error) {
                // Silent error handling - don't break the form if custom code fails
                if (typeof console !== 'undefined' && console.error) {
                    console.error('Error executing custom GA event:', triggerName, error);
                }
            }
        }
    }
    
    // Make trackEvent available globally for custom triggers
    window.trackEvent = trackEvent;

    // Password toggle functionality
    const toggleButtons = document.querySelectorAll('.toggle-password');
    toggleButtons.forEach(button => {
        button.addEventListener('click', function() {
            const passwordField = this.parentElement.querySelector('input[name="password"]');
            const eyeIcon = this.querySelector('.eye-icon');
            
            if (!passwordField || !eyeIcon) return;
            
            // Toggle password visibility
            if (passwordField.type === 'password') {
                passwordField.type = 'text';
                eyeIcon.innerHTML = `
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640"><path d="M73 39.1C63.6 29.7 48.4 29.7 39.1 39.1C29.8 48.5 29.7 63.7 39 73.1L567 601.1C576.4 610.5 591.6 610.5 600.9 601.1C610.2 591.7 610.3 576.5 600.9 567.2L504.5 470.8C507.2 468.4 509.9 466 512.5 463.6C559.3 420.1 590.6 368.2 605.5 332.5C608.8 324.6 608.8 315.8 605.5 307.9C590.6 272.2 559.3 220.2 512.5 176.8C465.4 133.1 400.7 96.2 319.9 96.2C263.1 96.2 214.3 114.4 173.9 140.4L73 39.1zM208.9 175.1C241 156.2 278.1 144 320 144C385.2 144 438.8 173.6 479.9 211.7C518.4 247.4 545 290 558.5 320C544.9 350 518.3 392.5 479.9 428.3C476.8 431.1 473.7 433.9 470.5 436.7L425.8 392C439.8 371.5 448 346.7 448 320C448 249.3 390.7 192 320 192C293.3 192 268.5 200.2 248 214.2L208.9 175.1zM390.9 357.1L282.9 249.1C294 243.3 306.6 240 320 240C364.2 240 400 275.8 400 320C400 333.4 396.7 346 390.9 357.1zM135.4 237.2L101.4 203.2C68.8 240 46.4 279 34.5 307.7C31.2 315.6 31.2 324.4 34.5 332.3C49.4 368 80.7 420 127.5 463.4C174.6 507.1 239.3 544 320.1 544C357.4 544 391.3 536.1 421.6 523.4L384.2 486C364.2 492.4 342.8 496 320 496C254.8 496 201.2 466.4 160.1 428.3C121.6 392.6 95 350 81.5 320C91.9 296.9 110.1 266.4 135.5 237.2z"/></svg>
                `;
            } else {
                passwordField.type = 'password';
                eyeIcon.innerHTML = `
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640"><path d="M320 144C254.8 144 201.2 173.6 160.1 211.7C121.6 247.5 95 290 81.4 320C95 350 121.6 392.5 160.1 428.3C201.2 466.4 254.8 496 320 496C385.2 496 438.8 466.4 479.9 428.3C518.4 392.5 545 350 558.6 320C545 290 518.4 247.5 479.9 211.7C438.8 173.6 385.2 144 320 144zM127.4 176.6C174.5 132.8 239.2 96 320 96C400.8 96 465.5 132.8 512.6 176.6C559.4 220.1 590.7 272 605.6 307.7C608.9 315.6 608.9 324.4 605.6 332.3C590.7 368 559.4 420 512.6 463.4C465.5 507.1 400.8 544 320 544C239.2 544 174.5 507.2 127.4 463.4C80.6 419.9 49.3 368 34.4 332.3C31.1 324.4 31.1 315.6 34.4 307.7C49.3 272 80.6 220 127.4 176.6zM320 400C364.2 400 400 364.2 400 320C400 290.4 383.9 264.5 360 250.7C358.6 310.4 310.4 358.6 250.7 360C264.5 383.9 290.4 400 320 400zM240.4 311.6C242.9 311.9 245.4 312 248 312C283.3 312 312 283.3 312 248C312 245.4 311.8 242.9 311.6 240.4C274.2 244.3 244.4 274.1 240.5 311.5zM286 196.6C296.8 193.6 308.2 192.1 319.9 192.1C328.7 192.1 337.4 193 345.7 194.7C346 194.8 346.2 194.8 346.5 194.9C404.4 207.1 447.9 258.6 447.9 320.1C447.9 390.8 390.6 448.1 319.9 448.1C258.3 448.1 206.9 404.6 194.7 346.7C192.9 338.1 191.9 329.2 191.9 320.1C191.9 309.1 193.3 298.3 195.9 288.1C196.1 287.4 196.2 286.8 196.4 286.2C208.3 242.8 242.5 208.6 285.9 196.7z"/></svg>
                `;
            }
        });
    });

    // Social login buttons - Basic functionality only
    const googleButtons = document.querySelectorAll('.google-btn');
    googleButtons.forEach(button => {
        button.addEventListener('click', function() {
            trackEvent('social_login_click');
            showMessage('Google Sign-In not configured yet.', 'info');
        });
    });

    const appleButtons = document.querySelectorAll('.apple-btn');
    appleButtons.forEach(button => {
        button.addEventListener('click', function() {
            trackEvent('social_login_click');
            showMessage('Apple Sign-In not configured yet.', 'info');
        });
    });

    // Real-time form validation
    function validateForm() {
        const forms = document.querySelectorAll('.signup-form');
        forms.forEach(form => {
            const emailInput = form.querySelector('input[name="email"]');
            const passwordInput = form.querySelector('input[name="password"]');
            const submitButton = form.querySelector('.submit-button');
            const termsCheckbox = form.querySelector('input[type="checkbox"]');
            
            if (emailInput && passwordInput && submitButton) {
                let firstInteraction = false;
                
                function checkFormValidity() {
                    const email = emailInput.value.trim();
                    const password = passwordInput.value.trim();
                    const termsAccepted = termsCheckbox ? termsCheckbox.checked : true;
                    
                    // Check reCAPTCHA if present
                    const recaptchaResponse = getRecaptchaResponse();
                    const recaptchaValid = !hasRecaptcha() || recaptchaResponse;
                    
                    const isValid = email.length > 0 && 
                                  password.length >= 6 && 
                                  isValidEmail(email) && 
                                  termsAccepted &&
                                  recaptchaValid;
                    
                    if (isValid) {
                        submitButton.style.backgroundColor = '#007cba';
                        submitButton.style.opacity = '1';
                        submitButton.disabled = false;
                    } else {
                        submitButton.style.backgroundColor = '#ccc';
                        submitButton.style.opacity = '0.6';
                        submitButton.disabled = false; // Keep button enabled but show error on click
                    }
                }
                
                // Track form interaction (first step)
                function trackFirstInteraction() {
                    if (!firstInteraction) {
                        firstInteraction = true;
                        trackEvent('form_start');
                        trackEvent('conversion');
                    }
                }
                
                // Add event listeners for real-time validation
                emailInput.addEventListener('input', function() {
                    trackFirstInteraction();
                    checkFormValidity();
                });
                passwordInput.addEventListener('input', function() {
                    trackFirstInteraction();
                    checkFormValidity();
                });
                if (termsCheckbox) {
                    termsCheckbox.addEventListener('change', function() {
                        trackFirstInteraction();
                        checkFormValidity();
                    });
                }
                
                // Track form click
                form.addEventListener('click', function() {
                    trackEvent('form_click');
                });
                
                // Handle submit button clicks - show error if form is invalid
                submitButton.addEventListener('click', function(e) {
                    // Check if form is valid
                    const email = emailInput.value.trim();
                    const password = passwordInput.value.trim();
                    const termsAccepted = termsCheckbox ? termsCheckbox.checked : true;
                    const recaptchaResponse = getRecaptchaResponse();
                    const recaptchaValid = !hasRecaptcha() || recaptchaResponse;
                    
                    const isValid = email.length > 0 && 
                                  password.length >= 6 && 
                                  isValidEmail(email) && 
                                  termsAccepted &&
                                  recaptchaValid;
                    
                    if (!isValid) {
                        e.preventDefault();
                        e.stopPropagation();
                        
                        let errorMessage = '';
                        
                        if (!email && !password) {
                            errorMessage = 'Please enter your email and password to continue.';
                            trackEvent('form_error');
                        } else if (!email) {
                            errorMessage = 'Please enter your email address.';
                            trackEvent('form_error');
                        } else if (!password) {
                            errorMessage = 'Please enter a password.';
                            trackEvent('form_error');
                        } else if (!isValidEmail(email)) {
                            errorMessage = 'Please enter a valid email address.';
                            trackEvent('form_error');
                        } else if (password.length < 6) {
                            errorMessage = 'Password must be at least 6 characters long.';
                            trackEvent('form_error');
                        } else if (!termsAccepted) {
                            errorMessage = 'Please accept the terms and conditions.';
                            trackEvent('form_error');
                        } else if (!recaptchaValid) {
                            errorMessage = 'Please complete the reCAPTCHA verification.';
                            trackEvent('form_error');
                        }
                        
                        if (errorMessage) {
                            showMessage(errorMessage, 'error');
                        }
                    }
                });
                
                // Initial check
                checkFormValidity();
            }
        });
    }
    
    // Initialize form validation
    validateForm();

    // Form submission handling - Basic validation only
    const signupForms = document.querySelectorAll('.signup-form');
    signupForms.forEach(form => {
        form.addEventListener('submit', function(e) {
            const email = this.querySelector('input[name="email"]').value;
            const password = this.querySelector('input[name="password"]').value;
            const recaptchaResponse = getRecaptchaResponse();
            const recaptchaValid = !hasRecaptcha() || recaptchaResponse;
            
            // Track form submission attempt
            trackEvent('form_submit_attempt');
            
            // Basic validation
            if (!email || !password) {
                e.preventDefault();
                trackEvent('form_error');
                showMessage('Please fill in all required fields.', 'error');
                return;
            }
            
            if (!isValidEmail(email)) {
                e.preventDefault();
                trackEvent('form_error');
                showMessage('Please enter a valid email address.', 'error');
                return;
            }
            
            if (password.length < 6) {
                e.preventDefault();
                trackEvent('form_error');
                showMessage('Password must be at least 6 characters long.', 'error');
                return;
            }
            
            if (!recaptchaValid) {
                e.preventDefault();
                trackEvent('form_error');
                showMessage('Please complete the reCAPTCHA verification.', 'error');
                return;
            }
            
            // If validation passes, track successful submission
            trackEvent('form_submit_success');
            trackEvent('conversion');
            
            showMessage('Form submitted successfully!', 'success');
        });
    });


    // Utility functions
    function isValidEmail(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    }

    // reCAPTCHA v3 helper functions
    function hasRecaptcha() {
        return document.getElementById('recaptcha_response') !== null;
    }

    function getRecaptchaResponse() {
        const recaptchaInput = document.getElementById('recaptcha_response');
        return recaptchaInput ? recaptchaInput.value : '';
    }

    // Regenerate reCAPTCHA token if needed
    function refreshRecaptchaToken() {
        if (hasRecaptcha() && typeof grecaptcha !== 'undefined') {
            grecaptcha.ready(function() {
                grecaptcha.execute(window.recaptchaSiteKey, {action: 'signup'}).then(function(token) {
                    const recaptchaInput = document.getElementById('recaptcha_response');
                    if (recaptchaInput) {
                        recaptchaInput.value = token;
                    }
                });
            });
        }
    }


    function showMessage(message, type = 'info') {
        // Remove existing messages
        const existingMessages = document.querySelectorAll('.signup-message');
        existingMessages.forEach(msg => msg.remove());
        
        // Create new message element
        const messageEl = document.createElement('div');
        messageEl.className = `signup-message signup-message-${type}`;
        messageEl.textContent = message;
        
        // Add styles
        messageEl.style.cssText = `
            padding: 12px 16px;
            margin: 16px 0;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            text-align: center;
            ${type === 'success' ? 
                'background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb;' : 
                type === 'error' ? 
                'background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb;' :
                'background-color: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb;'
            }
        `;
        
        // Insert message
        const form = document.querySelector('.signup-form');
        if (form) {
            form.parentNode.insertBefore(messageEl, form);
            
            // Auto-remove after 5 seconds
            setTimeout(() => {
                if (messageEl.parentNode) {
                    messageEl.remove();
                }
            }, 5000);
        }
    }
});