/* Book Discovery Contact Form Component */

const { useState } = React;

function BookDiscoveryForm({ isOpen, onClose }) {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    company: '',
    message: ''
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [error, setError] = useState('');

  const handleChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsSubmitting(true);
    setError('');

    // Create email body
    const emailBody = `
Discovery Call Request - Formedium Proposal

Name: ${formData.name}
Email: ${formData.email}
Phone: ${formData.phone}
Company: ${formData.company}

Project Details:
${formData.message}

---
Submitted from: Formedium × RVS Media Proposal
Time: ${new Date().toLocaleString()}
    `.trim();

    try {
      // Option 1: Try Formspree if configured
      if (window.FORMSPREE_ENDPOINT) {
        const response = await fetch(window.FORMSPREE_ENDPOINT, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            name: formData.name,
            email: formData.email,
            phone: formData.phone,
            company: formData.company,
            message: emailBody,
            subject: 'New Discovery Call Request - Formedium Proposal',
            _replyto: formData.email
          })
        });

        if (response.ok) {
          setIsSubmitted(true);
          setTimeout(() => {
            setIsSubmitted(false);
            setFormData({ name: '', email: '', phone: '', company: '', message: '' });
            onClose();
          }, 3000);
          return;
        }
      }

      // Option 2: Fallback to mailto
      const mailtoLink = `mailto:rajeev@rvsmedia.com?subject=${encodeURIComponent('Discovery Call Request - Formedium Proposal')}&body=${encodeURIComponent(emailBody)}`;
      window.location.href = mailtoLink;

      setIsSubmitted(true);
      setTimeout(() => {
        setIsSubmitted(false);
        setFormData({ name: '', email: '', phone: '', company: '', message: '' });
        onClose();
      }, 3000);

    } catch (err) {
      setError('Sorry, there was an error sending your message. Please try again or email us directly at rajeev@rvsmedia.com');
      console.error('Form submission error:', err);
    } finally {
      setIsSubmitting(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="form-overlay" onClick={onClose}>
      <div className="form-modal" onClick={(e) => e.stopPropagation()}>
        <div className="form-header">
          <h2>Book a Discovery Call</h2>
          <p>Let's discuss your B2B platform requirements</p>
          <button className="form-close" onClick={onClose}>×</button>
        </div>

        {isSubmitted ? (
          <div className="form-success">
            <div className="success-icon">✓</div>
            <h3>Thank you!</h3>
            <p>We've received your request and will contact you within 24 hours to schedule your discovery call.</p>
          </div>
        ) : (
          <form onSubmit={handleSubmit} className="discovery-form">
            <div className="form-row">
              <div className="form-group">
                <label htmlFor="name">Full Name *</label>
                <input
                  type="text"
                  id="name"
                  name="name"
                  value={formData.name}
                  onChange={handleChange}
                  required
                  placeholder="Your full name"
                />
              </div>
              <div className="form-group">
                <label htmlFor="company">Company</label>
                <input
                  type="text"
                  id="company"
                  name="company"
                  value={formData.company}
                  onChange={handleChange}
                  placeholder="Company name"
                />
              </div>
            </div>

            <div className="form-row">
              <div className="form-group">
                <label htmlFor="email">Email Address *</label>
                <input
                  type="email"
                  id="email"
                  name="email"
                  value={formData.email}
                  onChange={handleChange}
                  required
                  placeholder="your@email.com"
                />
              </div>
              <div className="form-group">
                <label htmlFor="phone">Phone Number</label>
                <input
                  type="tel"
                  id="phone"
                  name="phone"
                  value={formData.phone}
                  onChange={handleChange}
                  placeholder="+44 123 456 7890"
                />
              </div>
            </div>

            <div className="form-group">
              <label htmlFor="message">Project Details</label>
              <textarea
                id="message"
                name="message"
                value={formData.message}
                onChange={handleChange}
                rows="4"
                placeholder="Tell us about your current platform, key challenges, and what you're hoping to achieve..."
              ></textarea>
            </div>

            {error && (
              <div className="form-error">
                {error}
              </div>
            )}

            <div className="form-actions">
              <button type="button" onClick={onClose} className="btn ghost">
                Cancel
              </button>
              <button type="submit" disabled={isSubmitting} className="btn accent">
                {isSubmitting ? 'Sending...' : 'Book Discovery Call →'}
              </button>
            </div>

            <div className="form-footer">
              <p>We'll contact you within 24 hours to schedule a convenient time for your discovery call.</p>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

// Global form state management
let globalFormState = {
  isOpen: false,
  setIsOpen: null
};

function ContactFormManager() {
  const [isFormOpen, setIsFormOpen] = useState(false);

  React.useEffect(() => {
    globalFormState.setIsOpen = setIsFormOpen;

    // Handle Book Discovery button clicks
    const handleBookDiscovery = (e) => {
      e.preventDefault();
      setIsFormOpen(true);
    };

    // Find and attach event listeners to Book Discovery buttons
    const bookButtons = document.querySelectorAll('a[href="#next"], .book-discovery-btn');
    bookButtons.forEach(button => {
      button.addEventListener('click', handleBookDiscovery);
    });

    // Cleanup
    return () => {
      bookButtons.forEach(button => {
        button.removeEventListener('click', handleBookDiscovery);
      });
    };
  }, []);

  return (
    <BookDiscoveryForm
      isOpen={isFormOpen}
      onClose={() => setIsFormOpen(false)}
    />
  );
}

// Export components to global scope
window.BookDiscoveryForm = BookDiscoveryForm;
window.ContactFormManager = ContactFormManager;