/* Professor's Transport — Driver / staff application modal */
const { useState: useStateApply, useEffect: useEffectApply, useRef: useRefApply } = React;

// ----- Where applications are sent -----
// Web3Forms supports file attachments from a static site (no backend).
// 1) Get a free access key at https://web3forms.com (enter the destination email).
// 2) Paste it below. Until then the form runs in DEMO mode (no real email is sent).
const WEB3FORMS_KEY = "65c13ba8-f9c9-4f4c-bd38-55955fc17679";
const APPLY_MAX_MB = 10; // Web3Forms free tier attachment ceiling
const APPLY_MAX_FILES = 6;
const APPLY_ALLOWED_EXT = [".pdf", ".jpg", ".jpeg", ".png", ".doc", ".docx"];

function hasAllowedExtension(fileName) {
  const lower = String(fileName || "").toLowerCase();
  return APPLY_ALLOWED_EXT.some((ext) => lower.endsWith(ext));
}

function ApplyModal({ open, position, onClose }) {
  const [files, setFiles] = useStateApply([]);
  const [status, setStatus] = useStateApply("idle"); // idle | sending | success | error
  const [errorMsg, setErrorMsg] = useStateApply("");
  const fileInputRef = useRefApply(null);

  // Reset when (re)opened
  useEffectApply(() => {
    if (open) { setStatus("idle"); setFiles([]); setErrorMsg(""); }
  }, [open, position]);

  // Esc to close + body scroll lock
  useEffectApply(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [open, onClose]);

  if (!open) return null;

  const totalMB = files.reduce((s, f) => s + f.size, 0) / (1024 * 1024);
  const isDriver = position !== "Corporate";

  function addFiles(list) {
    const incoming = Array.from(list);
    const rejected = incoming.filter((f) => !hasAllowedExtension(f.name));
    const validIncoming = incoming.filter((f) => hasAllowedExtension(f.name));

    if (rejected.length) {
      setStatus("error");
      setErrorMsg("Some files were rejected. Allowed: PDF, JPG, PNG, DOC, DOCX.");
    }

    setFiles((prev) => {
      const names = new Set(prev.map((f) => f.name + f.size));
      const merged = [...prev];
      validIncoming.forEach((f) => { if (!names.has(f.name + f.size)) merged.push(f); });
      if (merged.length > APPLY_MAX_FILES) {
        setStatus("error");
        setErrorMsg(`You can upload up to ${APPLY_MAX_FILES} files.`);
        return merged.slice(0, APPLY_MAX_FILES);
      }
      return merged;
    });
  }
  function removeFile(idx) {
    setFiles((prev) => prev.filter((_, i) => i !== idx));
  }

  async function submit(ev) {
    ev.preventDefault();
    if (status === "sending") return;
    const formEl = ev.target;
    const fd = new FormData(formEl);

    const fullName = String(fd.get("Name") || "").trim();
    const phone = String(fd.get("Phone") || "").trim();
    const email = String(fd.get("email") || "").trim();
    const notes = String(fd.get("Notes") || "").trim();
    const website = String(fd.get("website") || "").trim();

    if (website) {
      setStatus("error");
      setErrorMsg("Submission blocked. Please refresh and try again.");
      return;
    }
    if (fullName.length < 2) {
      setStatus("error");
      setErrorMsg("Please enter your full name.");
      return;
    }
    if (!/^[0-9+()\-\s]{10,20}$/.test(phone)) {
      setStatus("error");
      setErrorMsg("Please enter a valid phone number.");
      return;
    }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      setStatus("error");
      setErrorMsg("Please enter a valid email address.");
      return;
    }
    if (notes.length > 1000) {
      setStatus("error");
      setErrorMsg("Notes are too long. Please keep notes under 1000 characters.");
      return;
    }
    if (files.length > APPLY_MAX_FILES) {
      setStatus("error");
      setErrorMsg(`You can upload up to ${APPLY_MAX_FILES} files.`);
      return;
    }
    if (files.some((f) => !hasAllowedExtension(f.name))) {
      setStatus("error");
      setErrorMsg("One or more attachments have an unsupported file type.");
      return;
    }
    if (totalMB > APPLY_MAX_MB) {
      setStatus("error");
      setErrorMsg(`Attachments total ${totalMB.toFixed(1)} MB — please keep under ${APPLY_MAX_MB} MB.`);
      return;
    }

    setErrorMsg("");
    fd.set("Position", position);
    fd.set("subject", `Driver application — ${position}`);
    fd.set("from_name", "Professor's Transport careers");
    files.forEach((f) => fd.append("attachment", f, f.name));

    setStatus("sending");

    // DEMO mode if no key configured — simulate a successful submission
    if (!WEB3FORMS_KEY || WEB3FORMS_KEY.startsWith("REPLACE_")) {
      console.warn("[ApplyModal] No Web3Forms key set — running in DEMO mode, nothing was emailed.");
      setTimeout(() => setStatus("success"), 900);
      return;
    }

    fd.set("access_key", WEB3FORMS_KEY);
    try {
      const res = await fetch("https://api.web3forms.com/submit", { method: "POST", body: fd });
      const data = await res.json();
      if (data.success) { setStatus("success"); setErrorMsg(""); }
      else { setStatus("error"); setErrorMsg(data.message || "Submission failed."); }
    } catch (err) {
      setStatus("error");
      setErrorMsg("Network error — please email careers@professorstransport.com or call +14375351330.");
    }
  }

  return (
    <div className="amodal" role="dialog" aria-modal="true" aria-label={`Apply — ${position}`}>
      <div className="amodal__backdrop" onClick={onClose}></div>
      <div className="amodal__card">
        <button type="button" className="amodal__close" aria-label="Close" onClick={onClose}>✕</button>

        {status === "success" ?
        <div className="amodal__success">
            <div className="amodal__success-mark">✓</div>
            <h3>Application received.</h3>
            <p>Thanks for applying for the <strong>{position}</strong> position. A recruiter will review your details and documents and call you within 24 hours. For anything urgent, call +14375351330.</p>
            <button type="button" className="btn btn--primary" onClick={onClose}>Done</button>
          </div> :

        <>
            <div className="amodal__head">
              <div className="amodal__eyebrow">Application · {position}</div>
              <h2 className="amodal__title">Apply to {isDriver ? "drive" : "join"} Professor's</h2>
              <p className="amodal__sub">Tell us about yourself and attach your documents. {isDriver ? "Class 1/A licence and CVOR abstract recommended." : "Attach a résumé and anything relevant."}</p>
            </div>

            <form className="amodal__form" onSubmit={submit}>
              <input
                type="text"
                name="website"
                tabIndex="-1"
                autoComplete="off"
                style={{ position: "absolute", left: "-9999px", opacity: 0 }}
                aria-hidden="true"
              />
              <div className="afield">
                <label>Position</label>
                <input type="text" name="Position label" value={position} readOnly className="afield__readonly" />
              </div>

              <div className="aform__row two">
                <div className="afield">
                  <label>Full name *</label>
                  <input type="text" name="Name" required placeholder="First and last name" minLength={2} maxLength={80} />
                </div>
                <div className="afield">
                  <label>Phone *</label>
                  <input type="tel" name="Phone" required placeholder="(000) 000-0000" pattern="^[0-9+()\-\s]{10,20}$" title="Use a valid phone number" />
                </div>
              </div>

              <div className="aform__row two">
                <div className="afield">
                  <label>Email *</label>
                  <input type="email" name="email" required placeholder="you@email.com" maxLength={120} />
                </div>
                <div className="afield">
                  <label>City / province</label>
                  <input type="text" name="Location" placeholder="e.g. Brampton, ON" maxLength={80} />
                </div>
              </div>

              {isDriver &&
              <div className="aform__row two">
                  <div className="afield">
                    <label>Licence class</label>
                    <select name="Licence class" defaultValue="AZ / Class 1">
                      <option>AZ / Class 1</option>
                      <option>DZ / Class 3</option>
                      <option>Other / In progress</option>
                    </select>
                  </div>
                  <div className="afield">
                    <label>Years of experience</label>
                    <select name="Experience" defaultValue="2–5 years">
                      <option>Less than 2 years</option>
                      <option>2–5 years</option>
                      <option>5–10 years</option>
                      <option>10+ years</option>
                    </select>
                  </div>
                </div>
              }

              {/* Document upload */}
              <div className="afield">
                <label>Documents {isDriver ? "(licence, CVOR abstract, résumé)" : "(résumé, cover letter)"}</label>
                <div
                  className="afile-drop"
                  onClick={() => fileInputRef.current && fileInputRef.current.click()}
                  onDragOver={(e) => { e.preventDefault(); e.currentTarget.classList.add("is-over"); }}
                  onDragLeave={(e) => e.currentTarget.classList.remove("is-over")}
                  onDrop={(e) => { e.preventDefault(); e.currentTarget.classList.remove("is-over"); addFiles(e.dataTransfer.files); }}>
                  <input
                    ref={fileInputRef}
                    type="file"
                    multiple
                    accept=".pdf,.jpg,.jpeg,.png,.doc,.docx"
                    style={{ display: "none" }}
                    onChange={(e) => addFiles(e.target.files)} />
                  <div className="afile-drop__icon">
                    <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.5">
                      <path d="M12 16V4M7 9l5-5 5 5" /><path d="M5 20h14" />
                    </svg>
                  </div>
                  <div className="afile-drop__text">
                    <strong>Click to upload</strong> or drag &amp; drop<br />
                    <span>PDF, JPG, PNG or DOC · up to {APPLY_MAX_MB} MB total</span>
                  </div>
                </div>

                {files.length > 0 &&
                <ul className="afile-list">
                    {files.map((f, i) =>
                  <li key={i}>
                        <span className="afile-list__name">{f.name}</span>
                        <span className="afile-list__size">{(f.size / 1024).toFixed(0)} KB</span>
                        <button type="button" aria-label="Remove" onClick={() => removeFile(i)}>✕</button>
                      </li>
                  )}
                  </ul>
                }
              </div>

              <div className="afield">
                <label>Anything else?</label>
                <textarea name="Notes" rows={2} placeholder="Availability, equipment preference, questions…" maxLength={1000}></textarea>
              </div>

              <div className="amodal__foot">
                <span className="amodal__meta">
                  {status === "error" ?
                  <span style={{ color: "oklch(0.6 0.2 25)" }}>{errorMsg}</span> :
                  <>We'll never share your details with brokers.</>}
                </span>
                <button type="submit" className="btn btn--primary" disabled={status === "sending"}>
                  {status === "sending" ? "Sending…" : <>Submit application <Icon.arrow /></>}
                </button>
              </div>
            </form>
          </>
        }
      </div>
    </div>);

}

Object.assign(window, { ApplyModal });
