document.addEventListener('alpine:init', () => {
  Alpine.data('contactForm', () => ({
    formData: {
      name: '',
      email: '',
      message: ''
    },
    isSubmitting: false,
    statusMessage: '',
    statusClass: '',
    loadedAt: Math.floor(Date.now() / 1000),

    async submitContactForm() {
      this.isSubmitting = true;
      this.statusMessage = '';
      this.statusClass = '';

      try {
        const formData = new FormData();
        formData.append('name', this.formData.name);
        formData.append('email', this.formData.email);
        formData.append('message', this.formData.message);
        formData.append('subject', '');
        formData.append('website', ''); // honeypot
        formData.append('_t', this.loadedAt); // timing check: when form loaded

        const response = await fetch('/api/contact.php', {
          method: 'POST',
          body: formData
        });

        const data = await response.json();

        if (response.ok) {
          this.statusMessage = 'Message sent successfully!';
          this.statusClass = 'bg-green-100 text-green-800 border border-green-300';
          this.formData = { name: '', email: '', message: '' };
        } else {
          this.statusMessage = data.error || 'An error occurred. Please try again.';
          this.statusClass = 'bg-red-100 text-red-800 border border-red-300';
        }
      } catch (error) {
        this.statusMessage = 'An error occurred. Please try again.';
        this.statusClass = 'bg-red-100 text-red-800 border border-red-300';
        console.error('Form submission error:', error);
      } finally {
        this.isSubmitting = false;
      }
    }
  }));
});
