function CandidateModal({ open, onClose }) {
  const [submitted, setSubmitted] = React.useState(false);
  const [uploading, setUploading] = React.useState(false);
  const [error, setError] = React.useState('');
  const [fileName, setFileName] = React.useState('');
  const [dragOver, setDragOver] = React.useState(false);
  const fileRef = React.useRef(null);
  const nameRef = React.useRef(null);
  const emailRef = React.useRef(null);
  const areaRef = React.useRef(null);

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

  const handleFile = (file) => {
    if (!file) return;
    const allowed = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
    if (!allowed.includes(file.type)) { setError('Please upload a PDF, DOC, or DOCX file.'); return; }
    if (file.size > 10 * 1024 * 1024) { setError('File must be under 10 MB.'); return; }
    setError('');
    setFileName(file.name);
    const dt = new DataTransfer();
    dt.items.add(file);
    fileRef.current.files = dt.files;
  };

  const handleDrop = (e) => {
    e.preventDefault();
    setDragOver(false);
    handleFile(e.dataTransfer.files[0]);
  };

  const handleSubmit = async () => {
    const name = nameRef.current.value.trim();
    const email = emailRef.current.value.trim();
    const area = areaRef.current.value;
    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; }
    const formData = new FormData();
    formData.append('name', name);
    formData.append('email', email);
    formData.append('area', area);
    if (fileRef.current.files[0]) formData.append('resume', fileRef.current.files[0]);
    setUploading(true);
    setError('');
    try {
      const res = await fetch('/api/candidate', { method: 'POST', body: formData });
      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 {
      setUploading(false);
    }
  };

  return (
    <div className={"modal-bg " + (open ? "open" : "")} onClick={onClose}>
      <div className="modal candidate-modal" onClick={e => e.stopPropagation()} style={{position:'relative'}}>
        <button className="modal__close" onClick={onClose} aria-label="Close"><Icon name="close" size={18}/></button>
        {!submitted ? (
          <>
            <div className="candidate-modal__header">
              <span className="candidate-modal__badge"><Icon name="user" size={14}/> For Candidates</span>
              <h3>Join the <em>Network.</em></h3>
              <p>Submit your profile and we'll connect you with relevant opportunities. All submissions are treated as strictly confidential.</p>
            </div>
            <div className="modal__row">
              <div>
                <label>Full name <span className="required">*</span></label>
                <input ref={nameRef} className="field" placeholder="Your full name"/>
              </div>
              <div>
                <label>Email <span className="required">*</span></label>
                <input ref={emailRef} className="field" type="email" placeholder="you@email.com"/>
              </div>
            </div>
            <label>Area of interest</label>
            <select ref={areaRef} className="field">
              <option value="">Select an area…</option>
              <option>AI &amp; Machine Learning</option>
              <option>Cloud &amp; Infrastructure</option>
              <option>Cybersecurity</option>
              <option>Product &amp; Program</option>
              <option>Technology Leadership</option>
              <option>Executive / C-Suite</option>
              <option>Other</option>
            </select>
            <label>Resume / CV</label>
            <div
              className={"file-drop" + (dragOver ? " file-drop--over" : "") + (fileName ? " file-drop--filled" : "")}
              onClick={() => fileRef.current.click()}
              onDragOver={e => { e.preventDefault(); setDragOver(true); }}
              onDragLeave={() => setDragOver(false)}
              onDrop={handleDrop}
            >
              <input
                ref={fileRef}
                type="file"
                accept=".pdf,.doc,.docx"
                style={{display:'none'}}
                onChange={e => handleFile(e.target.files[0])}
              />
              {fileName ? (
                <div className="file-drop__content">
                  <Icon name="paperclip" size={18}/>
                  <span className="file-drop__name">{fileName}</span>
                  <button className="file-drop__remove" onClick={e => { e.stopPropagation(); setFileName(''); fileRef.current.value = ''; }} aria-label="Remove file">
                    <Icon name="close" size={14}/>
                  </button>
                </div>
              ) : (
                <div className="file-drop__content file-drop__content--empty">
                  <Icon name="upload" size={22}/>
                  <span>Drop your file here or <strong>browse</strong></span>
                  <small>PDF, DOC, DOCX &middot; Max 10 MB</small>
                </div>
              )}
            </div>
            {error && <p className="form-error">{error}</p>}
            <button
              className={"btn btn--blue candidate-modal__submit" + (uploading ? " btn--loading" : "")}
              onClick={handleSubmit}
              disabled={uploading}
            >
              {uploading ? 'Submitting…' : <><span>Submit Profile</span> <span className="arrow">&#8594;</span></>}
            </button>
          </>
        ) : (
          <div className="modal__success">
            <Icon name="checkCircle" size={56}/>
            <h3>You're in the <em>network.</em></h3>
            <p>We'll be in touch when a relevant opportunity arises. All profiles are treated as strictly confidential.</p>
            <button className="btn btn--outline" onClick={onClose} style={{marginTop:8}}>Close</button>
          </div>
        )}
      </div>
    </div>
  );
}

window.CandidateModal = CandidateModal;
