window.AnalyzerForm = function AnalyzerForm() {
  const [formData, setFormData] = React.useState({ url: '', email: '' });
  const [status, setStatus] = React.useState('idle'); // idle, loading, success, error
  const [errorMsg, setErrorMsg] = React.useState('');

  const webhookUrl = 'https://support-18044.n8n-wsk.com/form/1a787b8c-d179-4743-81c9-ee7b55287992';

  const validateEmail = (email) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  const validateUrl = (url) => {
    try {
      new URL(url.startsWith('http') ? url : `https://${url}`);
      return true;
    } catch {
      return false;
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setErrorMsg('');

    if (!validateUrl(formData.url)) {
      setErrorMsg('Please enter a valid website URL.');
      return;
    }

    if (!validateEmail(formData.email)) {
      setErrorMsg('Please enter a valid email address.');
      return;
    }

    setStatus('loading');

    // Format URL correctly before sending
    const formattedUrl = formData.url.startsWith('http') ? formData.url : `https://${formData.url}`;

    try {
      const response = await fetch(webhookUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          website: formattedUrl,
          email: formData.email
        }),
      });

      if (!response.ok) throw new Error('Failed to submit');

      setStatus('success');
      setFormData({ url: '', email: '' });
    } catch (err) {
      console.error(err);
      setStatus('error');
      setErrorMsg('An error occurred while submitting. Please try again.');
    }
  };

  return (
    <section id="analyzer-form" className="section" style={{ position: 'relative' }}>
      <div className="container" style={{ maxWidth: '800px' }}>
        <div className="glass reveal" style={{
          padding: '64px 48px',
          borderRadius: '32px',
          position: 'relative',
          overflow: 'hidden'
        }}>
          {status === 'loading' && (
            <div style={{
              position: 'absolute',
              top: 0, left: 0, right: 0,
              height: '4px',
              background: 'var(--input-border)',
              overflow: 'hidden'
            }}>
              <div style={{
                position: 'absolute',
                top: 0, left: 0, bottom: 0,
                width: '50%',
                background: 'var(--accent-gradient)',
                animation: 'progress 1.5s infinite ease-in-out'
              }}></div>
            </div>
          )}

          <style>
            {`@keyframes progress { 
              0% { left: -50%; width: 50%; } 
              100% { left: 100%; width: 50%; } 
            }`}
          </style>

          <div style={{ textAlign: 'center', marginBottom: '40px' }}>
            <h2 style={{ fontSize: '2.5rem', fontWeight: '700', marginBottom: '16px' }}>
              Ready to <span className="bg-gradient-text">analyze</span> your site?
            </h2>
            <p style={{ color: 'var(--text-secondary)', fontSize: '1.125rem' }}>
              Drop your link below and our AI will start auditing instantly.
            </p>
          </div>

          {status === 'success' ? (
            <div style={{
              padding: '32px',
              background: 'rgba(16, 185, 129, 0.1)',
              border: '1px solid rgba(16, 185, 129, 0.2)',
              borderRadius: '16px',
              textAlign: 'center',
              color: '#10b981'
            }}>
              <svg width="48" height="48" fill="none" stroke="currentColor" viewBox="0 0 24 24" style={{ margin: '0 auto 16px auto', display: 'block' }}>
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
              </svg>
              <h3 style={{ fontSize: '1.5rem', marginBottom: '8px' }}>Analysis Submitted!</h3>
              <p>Your UI analysis has started. Results will be sent to your email.</p>
              <button
                onClick={() => setStatus('idle')}
                className="btn btn-secondary"
                style={{ marginTop: '24px' }}
              >
                Analyze Another
              </button>
            </div>
          ) : (
            <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
              <div className="input-wrapper" style={{ margin: 0 }}>
                <label style={{ display: 'block', marginBottom: '8px', fontWeight: '500', color: 'var(--text-secondary)' }}>Website URL</label>
                <input
                  type="text"
                  name="website"
                  placeholder="e.g. yoursite.com"
                  className="input-field"
                  value={formData.url}
                  onChange={(e) => setFormData({ ...formData, url: e.target.value })}
                  disabled={status === 'loading'}
                  required
                />
              </div>

              <div className="input-wrapper" style={{ margin: 0 }}>
                <label style={{ display: 'block', marginBottom: '8px', fontWeight: '500', color: 'var(--text-secondary)' }}>Email Address</label>
                <input
                  type="email"
                  name="email"
                  placeholder="you@company.com"
                  className="input-field"
                  value={formData.email}
                  onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                  disabled={status === 'loading'}
                  required
                />
              </div>

              {errorMsg && (
                <div style={{ color: '#ef4444', fontSize: '0.875rem', marginTop: '-8px' }}>
                  {errorMsg}
                </div>
              )}

              <button
                type="submit"
                className="btn btn-primary"
                style={{ width: '100%', padding: '16px', fontSize: '1.125rem', marginTop: '8px', position: 'relative' }}
                disabled={status === 'loading'}
              >
                {status === 'loading' ? (
                  <span style={{ opacity: 0.8 }}>Analyzing...</span>
                ) : (
                  <span>Submit for Analysis</span>
                )}
              </button>
            </form>
          )}
        </div>
      </div>
    </section>
  );
};
