// CareerApplicationForm.jsx
//
// Real, in-site application form - replaces the old "Apply via Email"
// mailto: link on CareersPage.jsx. Posts to the same /api/mail-handler.php
// endpoint DemoRequestForm.jsx uses (formType=career instead of demo), so
// there's one backend, one PHPMailer setup, one spam-guard implementation
// to maintain, not two.
//
// Deliberately reuses MAIL_ENDPOINT, TURNSTILE_SITE_KEY, loadTurnstileScript,
// and useTurnstile from DemoRequestForm.jsx as plain globals rather than
// redefining them - classic scripts on this site share one global lexical
// scope (see Navbar.jsx's header comment), and DemoRequestForm.jsx loads
// before this file in careers/index.html's script list specifically so
// this works, the same pattern NotFoundPage.jsx uses for REAL_MODULES and
// SolutionsIndexPage.jsx uses for SOLUTIONS.
//
// Resume validation mirrors the server's rules (PDF/DOC/DOCX, 5MB) so a
// visitor sees the real problem immediately instead of waiting on a round
// trip - but the server re-checks everything itself (real MIME-type
// sniffing, not just the extension a browser reports) since client-side
// checks are trivially bypassable.
//
// Loaded as a classic (non-module) Babel-transformed script - see
// index.html's header comment.

const MAX_RESUME_BYTES = 5 * 1024 * 1024;
const ALLOWED_RESUME_EXTENSIONS = [".pdf", ".doc", ".docx"];

function CareerApplicationForm({ role, onDone }) {
  const [form, setForm] = React.useState({ name: "", email: "", phone: "", message: "" });
  const [resumeFile, setResumeFile] = React.useState(null);
  const [honeypot, setHoneypot] = React.useState("");
  const [errors, setErrors] = React.useState({});
  const [status, setStatus] = React.useState("idle"); // idle | submitting | done | error
  const [serverMessage, setServerMessage] = React.useState("");
  const mountedAt = React.useRef(Date.now());
  const { containerRef, getToken } = useTurnstile();

  const update = (field) => (e) => setForm((f) => ({ ...f, [field]: e.target.value }));

  const handleFileChange = (e) => {
    const file = e.target.files && e.target.files[0];
    e.target.value = ""; // let the same file be re-selected after a validation error
    if (!file) return;

    const ext = "." + (file.name.split(".").pop() || "").toLowerCase();
    if (!ALLOWED_RESUME_EXTENSIONS.includes(ext)) {
      setErrors((er) => ({ ...er, resume: "Please upload a PDF or Word document (.pdf, .doc, .docx)." }));
      setResumeFile(null);
      return;
    }
    if (file.size > MAX_RESUME_BYTES) {
      setErrors((er) => ({ ...er, resume: "Resume must be under 5MB." }));
      setResumeFile(null);
      return;
    }
    setErrors((er) => {
      const next = { ...er };
      delete next.resume;
      return next;
    });
    setResumeFile(file);
  };

  const validate = () => {
    const next = {};
    if (!form.name.trim()) next.name = "Name is required.";
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) next.email = "Enter a valid email.";
    if (!resumeFile) next.resume = "Please attach your resume.";
    setErrors(next);
    return Object.keys(next).length === 0;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!validate()) return;

    setStatus("submitting");
    setServerMessage("");

    try {
      const token = await getToken();

      const body = new FormData();
      body.append("formType", "career");
      body.append("name", form.name);
      body.append("email", form.email);
      body.append("phone", form.phone);
      body.append("role", role);
      body.append("message", form.message);
      body.append("resume", resumeFile);
      body.append("company_website", honeypot);
      body.append("form_elapsed_ms", String(Date.now() - mountedAt.current));
      body.append("cf-turnstile-response", token);

      const res = await fetch(MAIL_ENDPOINT, { method: "POST", body });
      const data = await res.json();

      if (data.success) {
        setServerMessage(data.message || "");
        setStatus("done");
      } else {
        setServerMessage(data.message || "Something went wrong - please try again.");
        setStatus("error");
      }
    } catch (err) {
      setServerMessage("We couldn't reach the server - check your connection and try again.");
      setStatus("error");
    }
  };

  if (status === "done") {
    return (
      <div className="mt-6 rounded-card border border-emerald-200 bg-emerald-50 p-6 text-center">
        <svg className="mx-auto h-9 w-9 text-emerald-600" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <circle cx="12" cy="12" r="9" />
          <path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4" />
        </svg>
        <h4 className="mt-3 text-base font-bold text-brand-navy">Thanks, {form.name.split(" ")[0]}.</h4>
        <p className="mt-2 text-sm text-slate-600">
          {serverMessage || "We've got your application and will get back to you directly."}
        </p>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} noValidate className="mt-6 space-y-4 rounded-card border border-slate-200 bg-surface p-6">
      <div className="sr-only" aria-hidden="true">
        <label htmlFor={`company_website_${role}`}>Company Website</label>
        <input
          id={`company_website_${role}`}
          type="text"
          name="company_website"
          tabIndex={-1}
          autoComplete="off"
          value={honeypot}
          onChange={(e) => setHoneypot(e.target.value)}
        />
      </div>

      <div ref={containerRef} />

      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
        <div>
          <label className="text-sm font-semibold text-brand-navy">Full name *</label>
          <input
            type="text"
            value={form.name}
            onChange={update("name")}
            className="mt-1.5 w-full rounded-lg border border-slate-200 bg-white px-3.5 py-2.5 text-sm text-ink focus:border-brand-navy/40 focus:outline-none focus:ring-2 focus:ring-emerald-500/20"
            placeholder="Jane Patel"
          />
          {errors.name && <p className="mt-1 text-xs text-red-600">{errors.name}</p>}
        </div>
        <div>
          <label className="text-sm font-semibold text-brand-navy">Email *</label>
          <input
            type="email"
            value={form.email}
            onChange={update("email")}
            className="mt-1.5 w-full rounded-lg border border-slate-200 bg-white px-3.5 py-2.5 text-sm text-ink focus:border-brand-navy/40 focus:outline-none focus:ring-2 focus:ring-emerald-500/20"
            placeholder="jane@example.com"
          />
          {errors.email && <p className="mt-1 text-xs text-red-600">{errors.email}</p>}
        </div>
      </div>

      <div>
        <label className="text-sm font-semibold text-brand-navy">Phone (optional)</label>
        <input
          type="tel"
          value={form.phone}
          onChange={update("phone")}
          className="mt-1.5 w-full rounded-lg border border-slate-200 bg-white px-3.5 py-2.5 text-sm text-ink focus:border-brand-navy/40 focus:outline-none focus:ring-2 focus:ring-emerald-500/20"
          placeholder="+91 98765 43210"
        />
      </div>

      <div>
        <label className="text-sm font-semibold text-brand-navy">Resume *</label>
        <input
          type="file"
          accept=".pdf,.doc,.docx"
          onChange={handleFileChange}
          className="mt-1.5 block w-full text-sm text-slate-600 file:mr-3 file:rounded-lg file:border-0 file:bg-brand-navy file:px-3.5 file:py-2 file:text-sm file:font-semibold file:text-white hover:file:bg-brand-navy/90"
        />
        <p className="mt-1 text-xs text-slate-500">PDF or Word, up to 5MB.</p>
        {resumeFile && !errors.resume && <p className="mt-1 text-xs text-emerald-700">{resumeFile.name} selected.</p>}
        {errors.resume && <p className="mt-1 text-xs text-red-600">{errors.resume}</p>}
      </div>

      <div>
        <label className="text-sm font-semibold text-brand-navy">Anything else you'd like us to know? (optional)</label>
        <textarea
          value={form.message}
          onChange={update("message")}
          rows={3}
          className="mt-1.5 w-full rounded-lg border border-slate-200 bg-white px-3.5 py-2.5 text-sm text-ink focus:border-brand-navy/40 focus:outline-none focus:ring-2 focus:ring-emerald-500/20"
          placeholder="Portfolio link, notice period, anything relevant…"
        />
      </div>

      {status === "error" && (
        <p className="rounded-lg border border-red-200 bg-red-50 px-3.5 py-2.5 text-sm text-red-700">{serverMessage}</p>
      )}

      <div className="flex items-center gap-3">
        <button
          type="submit"
          disabled={status === "submitting"}
          className="rounded-card bg-emerald-600 px-6 py-3 text-sm font-semibold text-white shadow-card transition hover:bg-emerald-700 disabled:opacity-60"
        >
          {status === "submitting" ? "Submitting…" : "Submit Application"}
        </button>
        {onDone && (
          <button type="button" onClick={onDone} className="text-sm font-semibold text-slate-500 hover:text-slate-700">
            Cancel
          </button>
        )}
      </div>
    </form>
  );
}
