/* ═══════════════════════════════════════════
   Rta Labs — Contact Form
   With validation, states, and Turnstile
   ═══════════════════════════════════════════ */

function ContactForm({ theme = 'light' }) {
  const [formState, setFormState] = React.useState('idle'); // idle | submitting | success | error
  const [apiError, setApiError] = React.useState(null);
  const [fields, setFields] = React.useState({
    name: '', company: '', email: '', phone: '',
    securing: '', message: '',
  });
  const [errors, setErrors] = React.useState({});
  const [turnstileToken, setTurnstileToken] = React.useState(null);
  const turnstileRef = React.useRef(null);
  const turnstileWidgetId = React.useRef(null);

  // Mount Turnstile widget — re-renders when theme changes so the captcha matches the page
  React.useEffect(() => {
    let attempts = 0;
    const maxAttempts = 30;
    function tryRender() {
      if (window.turnstile && turnstileRef.current && turnstileWidgetId.current === null) {
        turnstileWidgetId.current = window.turnstile.render(turnstileRef.current, {
          sitekey: '0x4AAAAAADhiQ30IDxsD-MlI',
          theme: theme,
          callback: (token) => setTurnstileToken(token),
          'expired-callback': () => setTurnstileToken(null),
        });
      } else if (attempts < maxAttempts) {
        attempts++;
        setTimeout(tryRender, 300);
      }
    }
    tryRender();
    return () => {
      if (turnstileWidgetId.current !== null && window.turnstile) {
        try { window.turnstile.remove(turnstileWidgetId.current); } catch(e) {}
        turnstileWidgetId.current = null;
      }
    };
  }, [theme]);

  const updateField = (key, value) => {
    setFields(prev => ({ ...prev, [key]: value }));
    if (errors[key]) setErrors(prev => { const n = { ...prev }; delete n[key]; return n; });
    if (apiError) setApiError(null);
  };

  const validate = () => {
    const e = {};
    if (!fields.name.trim()) e.name = 'Name is required';
    if (!fields.company.trim()) e.company = 'Company is required';
    if (!fields.email.trim()) e.email = 'Work email is required';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(fields.email)) e.email = 'Please enter a valid email';
    if (!fields.securing.trim()) e.securing = 'Please describe what you are securing';
    return e;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setApiError(null);

    const validationErrors = validate();
    if (Object.keys(validationErrors).length > 0) {
      setErrors(validationErrors);
      return;
    }

    setFormState('submitting');

    try {
      const res = await fetch('/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...fields, turnstileToken }),
      });

      const data = await res.json();

      if (!res.ok) {
        throw new Error(data.error || 'Something went wrong. Please try again.');
      }

      setFormState('success');
    } catch (err) {
      setFormState('error');
      setApiError(err.message || 'Network error. Please check your connection.');

      // Reset Turnstile so user can retry
      if (window.turnstile && turnstileWidgetId.current !== null) {
        window.turnstile.reset(turnstileWidgetId.current);
        setTurnstileToken(null);
      }
    }
  };

  if (formState === 'success') {
    return (
      <div className="form-success" style={{ animation: 'fadeUp 0.6s cubic-bezier(0.16,1,0.3,1) forwards' }}>
        <div className="form-success-icon">
          <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <polyline points="6 11 10 15 16 7"></polyline>
          </svg>
        </div>
        <h3>Thank you.</h3>
        <p>We've received your request and will be in touch shortly.</p>
        <button
          className="btn btn-secondary"
          style={{ marginTop: 28 }}
          onClick={() => {
            setFormState('idle');
            setApiError(null);
            setFields({ name: '', company: '', email: '', phone: '', securing: '', message: '' });
            setErrors({});
            setTurnstileToken(null);
            if (window.turnstile && turnstileWidgetId.current !== null) {
              window.turnstile.reset(turnstileWidgetId.current);
            }
          }}
        >Send another message</button>
      </div>
    );
  }

  return (
    <form className="form-grid" onSubmit={handleSubmit} noValidate>
      {apiError && (
        <div className="form-field full">
          <div style={{
            background: 'rgba(239,68,68,0.08)',
            border: '1px solid rgba(239,68,68,0.25)',
            borderRadius: 8,
            padding: '12px 16px',
            color: '#ef4444',
            fontSize: 14,
            lineHeight: 1.5,
          }}>
            {apiError}
          </div>
        </div>
      )}
      <div className="form-field">
        <label className="form-label">Name</label>
        <input
          className={`form-input ${errors.name ? 'error' : ''}`}
          type="text" placeholder="Full name"
          value={fields.name}
          onChange={e => updateField('name', e.target.value)}
        />
        {errors.name && <span className="form-error">{errors.name}</span>}
      </div>
      <div className="form-field">
        <label className="form-label">Company</label>
        <input
          className={`form-input ${errors.company ? 'error' : ''}`}
          type="text" placeholder="Organization"
          value={fields.company}
          onChange={e => updateField('company', e.target.value)}
        />
        {errors.company && <span className="form-error">{errors.company}</span>}
      </div>
      <div className="form-field">
        <label className="form-label">Work Email</label>
        <input
          className={`form-input ${errors.email ? 'error' : ''}`}
          type="email" placeholder="you@company.com"
          value={fields.email}
          onChange={e => updateField('email', e.target.value)}
        />
        {errors.email && <span className="form-error">{errors.email}</span>}
      </div>
      <div className="form-field">
        <label className="form-label">Phone <span className="optional">(optional)</span></label>
        <input
          className="form-input"
          type="tel" placeholder="+91 ..."
          value={fields.phone}
          onChange={e => updateField('phone', e.target.value)}
        />
      </div>
      <div className="form-field full">
        <label className="form-label">What are you securing?</label>
        <textarea
          className={`form-textarea ${errors.securing ? 'error' : ''}`}
          placeholder="Applications, infrastructure, APIs, cloud environments..."
          rows="3"
          value={fields.securing}
          onChange={e => updateField('securing', e.target.value)}
        ></textarea>
        {errors.securing && <span className="form-error">{errors.securing}</span>}
      </div>
      <div className="form-field full">
        <label className="form-label">Message <span className="optional">(optional)</span></label>
        <textarea
          className="form-textarea"
          placeholder="Additional context or questions..."
          rows="3"
          value={fields.message}
          onChange={e => updateField('message', e.target.value)}
        ></textarea>
      </div>
      <div className="form-actions">
        <div className="turnstile-wrap" ref={turnstileRef}></div>
        <button
          type="submit"
          className="btn btn-primary"
          disabled={formState === 'submitting'}
          style={{ minWidth: 200, opacity: formState === 'submitting' ? 0.7 : 1 }}
        >
          {formState === 'submitting' ? (
            <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <svg width="16" height="16" viewBox="0 0 16 16" style={{ animation: 'spin 1s linear infinite' }}>
                <circle cx="8" cy="8" r="6" fill="none" stroke="currentColor" strokeWidth="2" strokeDasharray="28" strokeDashoffset="8" strokeLinecap="round"></circle>
              </svg>
              Submitting...
            </span>
          ) : 'Request Conversation'}
        </button>
      </div>
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </form>
  );
}

Object.assign(window, { ContactForm });
