function ConsultModal({ open, onClose }) {
  const [submitted, setSubmitted] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');
  const nameRef = React.useRef(null);
  const companyRef = React.useRef(null);
  const emailRef = React.useRef(null);
  const roleRef = React.useRef(null);

  React.useEffect(() => {
    if (!open) { setSubmitted(false); setError(''); setLoading(false); }
  }, [open]);

  const handleSubmit = async () => {
    const name = nameRef.current.value.trim();
    const company = companyRef.current.value.trim();
    const email = emailRef.current.value.trim();
    const role = roleRef.current.value.trim();
    if (!name || !email) { setError('Please fill in your name and email.'); return; }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { setError('Please enter a valid email address.'); return; }
    setLoading(true);
    setError('');
    try {
      const res = await fetch('/api/consult', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name, company, email, role }),
      });
      if (res.ok) { setSubmitted(true); }
      else { const d = await res.json().catch(() => ({})); setError(d.error || 'Submission failed. Please try again.'); }
    } catch (e) {
      setError('Network error. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={"modal-bg " + (open ? "open" : "")} onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{position:'relative'}}>
        <button className="modal__close" onClick={onClose} aria-label="Close"><Icon name="close" size={18}/></button>
        {!submitted ? (
          <>
            <h3>Schedule a <em>consultation.</em></h3>
            <p>Tell us about the role. A Synvori partner will be in touch within one business day.</p>
            <div className="modal__row">
              <div><label>Full name</label><input ref={nameRef} className="field" placeholder="Your name"/></div>
              <div><label>Company</label><input ref={companyRef} className="field" placeholder="Your company"/></div>
            </div>
            <label>Work email</label>
            <input ref={emailRef} className="field" type="email" placeholder="you@company.com"/>
            <label>What are you hiring for?</label>
            <input ref={roleRef} className="field" placeholder="e.g. Head of Platform Engineering"/>
            {error && <p className="form-error">{error}</p>}
            <button className="btn btn--ink" style={{width:'100%', justifyContent:'center', marginTop:8}} onClick={handleSubmit} disabled={loading}>
              {loading ? 'Sending…' : <><span>Request Consultation</span> <span className="arrow">&#8594;</span></>}
            </button>
          </>
        ) : (
          <div className="modal__success">
            <Icon name="checkCircle" size={56}/>
            <h3>Thank you.</h3>
            <p>A Synvori partner will reach out within one business day. All inquiries are treated as confidential.</p>
            <button className="btn btn--outline" onClick={onClose} style={{marginTop:8}}>Close</button>
          </div>
        )}
      </div>
    </div>
  );
}

window.ConsultModal = ConsultModal;
