// Contact form JavaScript for KLEINS REAL ESTATE

// DOM Ready
document.addEventListener('DOMContentLoaded', function() {
  // Initialize contact form
  initContactForm();
});

// Initialize contact form
function initContactForm() {
  // Prefill property ID if present in URL
  const urlParams = new URLSearchParams(window.location.search);
  const propertyId = urlParams.get('property_id');
  if (propertyId) {
    const propertyIdInput = document.getElementById('property-id');
    if (propertyIdInput) {
      propertyIdInput.value = propertyId;
    }
  }
  
  // Setup form submission handler
  const form = document.getElementById('contact-form');
  if (form) {
    form.addEventListener('submit', handleSubmit);
  }
  
  // Setup input validation
  setupValidation();
}

// Setup input validation
function setupValidation() {
  const inputs = document.querySelectorAll('#contact-form input, #contact-form textarea, #contact-form select');
  
  inputs.forEach(input => {
    // Validate on blur
    input.addEventListener('blur', function() {
      validateField(this);
    });
    
    // Clear error on input
    input.addEventListener('input', function() {
      clearError(this);
    });
  });
}

// Validate individual field
function validateField(field) {
  const fieldName = field.name;
  const value = field.value.trim();
  let isValid = true;
  let errorMessage = '';
  
  // Required fields
  if (field.hasAttribute('required') && !value) {
    isValid = false;
    errorMessage = `${getFieldLabel(fieldName)} is required`;
  }
  
  // Email validation
  if (fieldName === 'email' && value) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(value)) {
      isValid = false;
      errorMessage = 'Please enter a valid email address';
    }
  }
  
  // Show/hide error
  if (!isValid) {
    showError(field, errorMessage);
  } else {
    clearError(field);
  }
  
  return isValid;
}

// Get field label for error messages
function getFieldLabel(fieldName) {
  const labels = {
    'first-name': 'First name',
    'last-name': 'Last name',
    'email': 'Email',
    'type': 'Type',
    'message': 'Message'
  };
  
  return labels[fieldName] || fieldName;
}

// Show error for field
function showError(field, message) {
  field.classList.add('error');
  const errorElement = document.getElementById(`${field.name}-error`);
  if (errorElement) {
    errorElement.textContent = message;
    errorElement.classList.remove('hidden');
  }
}

// Clear error for field
function clearError(field) {
  field.classList.remove('error');
  const errorElement = document.getElementById(`${field.name}-error`);
  if (errorElement) {
    errorElement.classList.add('hidden');
  }
}

// Handle form submission
function handleSubmit(e) {
  e.preventDefault();
  
  // Validate all fields
  const form = document.getElementById('contact-form');
  const inputs = form.querySelectorAll('input, textarea, select');
  let isFormValid = true;
  
  inputs.forEach(input => {
    if (!validateField(input)) {
      isFormValid = false;
    }
  });
  
  // If form is invalid, scroll to first error
  if (!isFormValid) {
    const firstError = form.querySelector('.error');
    if (firstError) {
      firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
      firstError.focus();
    }
    return;
  }
  
  // Collect form data
  const formData = {
    firstName: document.getElementById('first-name').value,
    lastName: document.getElementById('last-name').value,
    email: document.getElementById('email').value,
    phone: document.getElementById('phone').value,
    type: document.getElementById('type').value,
    propertyId: document.getElementById('property-id').value,
    message: document.getElementById('message').value,
    timestamp: new Date().toISOString()
  };
  
  // Submit form
  submitForm(formData);
}

// Submit form data
function submitForm(data) {
  // Show loading state
  const submitButton = document.querySelector('button[type="submit"]');
  const submitText = document.getElementById('submit-text');
  const submitLoading = document.getElementById('submit-loading');
  
  if (submitButton) {
    submitButton.disabled = true;
  }
  
  if (submitText) {
    submitText.classList.add('hidden');
  }
  
  if (submitLoading) {
    submitLoading.classList.remove('hidden');
  }
  
  // Hide previous messages
  hideMessages();
  
  // Check if we have a submit URL
  if (KleinsApp.CONFIG.FORM_SUBMIT_URL) {
    // Submit to external URL
    submitToExternalUrl(data);
  } else {
    // Store in localStorage as fallback
    submitToLocalstorage(data);
  }
}

// Submit to external URL
function submitToExternalUrl(data) {
  fetch(KleinsApp.CONFIG.FORM_SUBMIT_URL, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  })
  .then(response => {
    if (response.ok) {
      showSuccessMessage();
      resetForm();
    } else {
      throw new Error('Submission failed');
    }
  })
  .catch(error => {
    console.error('Form submission error:', error);
    showErrorMessage();
  })
  .finally(() => {
    resetSubmitButton();
  });
}

// Submit to localStorage
function submitToLocalstorage(data) {
  try {
    // Get existing submissions
    const submissions = JSON.parse(localStorage.getItem('contactSubmissions') || '[]');
    
    // Add new submission
    submissions.push(data);
    
    // Save to localStorage
    localStorage.setItem('contactSubmissions', JSON.stringify(submissions));
    
    // Show success
    setTimeout(() => {
      showSuccessMessage();
      resetForm();
      resetSubmitButton();
    }, 1000);
  } catch (error) {
    console.error('LocalStorage error:', error);
    showErrorMessage();
    resetSubmitButton();
  }
}

// Show success message
function showSuccessMessage() {
  const successMessage = document.getElementById('success-message');
  if (successMessage) {
    successMessage.classList.remove('hidden');
    successMessage.scrollIntoView({ behavior: 'smooth' });
  }
}

// Show error message
function showErrorMessage() {
  const errorMessage = document.getElementById('error-message');
  if (errorMessage) {
    errorMessage.classList.remove('hidden');
    errorMessage.scrollIntoView({ behavior: 'smooth' });
  }
}

// Hide all messages
function hideMessages() {
  const successMessage = document.getElementById('success-message');
  const errorMessage = document.getElementById('error-message');
  
  if (successMessage) {
    successMessage.classList.add('hidden');
  }
  
  if (errorMessage) {
    errorMessage.classList.add('hidden');
  }
}

// Reset form
function resetForm() {
  const form = document.getElementById('contact-form');
  if (form) {
    form.reset();
    
    // Clear all errors
    const errorElements = form.querySelectorAll('.error');
    errorElements.forEach(element => {
      element.classList.remove('error');
    });
    
    const errorMessages = form.querySelectorAll('[id$="-error"]');
    errorMessages.forEach(element => {
      element.classList.add('hidden');
    });
  }
}

// Reset submit button
function resetSubmitButton() {
  const submitButton = document.querySelector('button[type="submit"]');
  const submitText = document.getElementById('submit-text');
  const submitLoading = document.getElementById('submit-loading');
  
  if (submitButton) {
    submitButton.disabled = false;
  }
  
  if (submitText) {
    submitText.classList.remove('hidden');
  }
  
  if (submitLoading) {
    submitLoading.classList.add('hidden');
  }
}