// ApplyModal.jsx — 2-step application form that actually submits to the backend.
const { useState: useStateM, useRef: useRefM } = React;

const API = 'http://localhost:3001';

// Inline SVG icons — lucide's createIcons() swaps <i> nodes out from under React,
// which crashes re-renders (e.g. step 1 → step 2). Keeping the modal's icons in JSX
// avoids the mismatch entirely.
const IconX = () => (
  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
);
const IconArrowRight = () => (
  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
);
const IconCheck = () => (
  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>
);

function ApplyModal({ open, onClose }) {
  const [step,      setStep]      = useStateM(1);
  const [done,      setDone]      = useStateM(false);
  const [loading,   setLoading]   = useStateM(false);
  const [errors,    setErrors]    = useStateM([]);

  // Step-1 controlled fields — values live in state, never read from DOM refs
  const [firstName, setFirstName] = useStateM('');
  const [lastName,  setLastName]  = useStateM('');
  const [email,     setEmail]     = useStateM('');
  const [grade,     setGrade]     = useStateM('5th grade');

  // Step-2 fields (only read on submit, refs are fine here)
  const motivationRef  = useRefM(null);
  const parentEmailRef = useRefM(null);

  function resetModal() {
    setStep(1); setDone(false); setErrors([]); setLoading(false);
    setFirstName(''); setLastName(''); setEmail(''); setGrade('5th grade');
  }

  function handleClose() { resetModal(); onClose(); }

  function handleStep1() {
    const e = [];
    if (!firstName.trim())  e.push('First name is required.');
    if (!lastName.trim())   e.push('Last name is required.');
    if (!email.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim()))
      e.push('A valid email is required.');
    if (e.length) { setErrors(e); return; }
    setErrors([]);
    setStep(2);
  }

  async function handleSubmit() {
    const motivation  = motivationRef.current?.value.trim();
    const parentEmail = parentEmailRef.current?.value.trim();

    const e = [];
    if (!motivation || motivation.length < 20) e.push('Please write at least a sentence about what pulls you to aerospace.');
    if (!parentEmail || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(parentEmail)) e.push('A valid parent/guardian email is required.');
    if (e.length) { setErrors(e); return; }

    setLoading(true);
    setErrors([]);

    try {
      const res = await fetch(`${API}/applications`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          firstName: firstName.trim(), lastName: lastName.trim(),
          email: email.trim(), grade, motivation, parentEmail,
        }),
      });

      const data = await res.json();

      if (!res.ok) {
        setErrors(data.errors ?? [data.error ?? 'Submission failed. Please try again.']);
        return;
      }

      setDone(true);
    } catch {
      setErrors(['Could not reach the server. Please check your connection and try again.']);
    } finally {
      setLoading(false);
    }
  }

  if (!open) return null;

  return (
    <div className="al-modal-scrim" onClick={handleClose}>
      <div className="al-modal" onClick={e => e.stopPropagation()}>
        <button type="button" className="al-modal-x" onClick={handleClose}><IconX/></button>

        {!done ? (
          <>
            <div className="al-eyebrow">APPLY · STEP {step} OF 2</div>
            <h3 className="al-modal-h">Join the next AeroLabs cohort</h3>
            <p className="al-modal-sub">Completely free. We reply within a week.</p>

            {errors.length > 0 && (
              <div className="al-modal-errors">
                {errors.map((err, i) => (
                  <p key={i}>{err}</p>
                ))}
              </div>
            )}

            {step === 1 ? (
              <div className="al-form">
                <div className="al-form-row">
                  <div className="al-field">
                    <label>First name</label>
                    <input
                      value={firstName}
                      onChange={e => setFirstName(e.target.value)}
                      placeholder="Saiyam"
                    />
                  </div>
                  <div className="al-field">
                    <label>Last name</label>
                    <input
                      value={lastName}
                      onChange={e => setLastName(e.target.value)}
                      placeholder="Sogani"
                    />
                  </div>
                </div>
                <div className="al-field">
                  <label>Your email</label>
                  <input
                    type="email"
                    value={email}
                    onChange={e => setEmail(e.target.value)}
                    placeholder="you@email.com"
                  />
                </div>
                <div className="al-field">
                  <label>Grade level</label>
                  <select value={grade} onChange={e => setGrade(e.target.value)}>
                    <option>5th grade</option><option>6th grade</option><option>7th grade</option>
                    <option>8th grade</option><option>9th grade</option><option>10th grade</option>
                    <option>11th grade</option><option>12th grade</option>
                  </select>
                </div>
                <div className="al-modal-actions">
                  <button type="button" className="al-btn al-btn-ghost" onClick={handleClose}>Cancel</button>
                  <button type="button" className="al-btn al-btn-primary" onClick={handleStep1}>
                    Continue <IconArrowRight/>
                  </button>
                </div>
              </div>
            ) : (
              <div className="al-form">
                <div className="al-field">
                  <label>What pulls you to aerospace?</label>
                  <textarea ref={motivationRef} rows={4} placeholder="A sentence or two is plenty. We read every one."/>
                </div>
                <div className="al-field">
                  <label>Parent/guardian email</label>
                  <input ref={parentEmailRef} type="email" placeholder="parent@email.com"/>
                </div>
                <div className="al-modal-actions">
                  <button type="button" className="al-btn al-btn-ghost" onClick={() => { setErrors([]); setStep(1); }}>Back</button>
                  <button type="button" className="al-btn al-btn-primary" onClick={handleSubmit} disabled={loading}>
                    {loading ? 'Submitting…' : 'Submit application'}
                  </button>
                </div>
              </div>
            )}
          </>
        ) : (
          <div className="al-modal-done">
            <div className="al-success-ring"><IconCheck/></div>
            <h3 className="al-modal-h">You're on the list.</h3>
            <p className="al-modal-sub">We'll email you within a week with next steps. Talk soon.</p>
            <button type="button" className="al-btn al-btn-primary" onClick={handleClose}>Close</button>
          </div>
        )}
      </div>
    </div>
  );
}
window.ApplyModal = ApplyModal;
