// ApplyModal.jsx — Application modal for open roles
// Mirrors the design language of ContactModal.jsx but with role-specific copy
// and a CV upload field. Submits via mailto: to contact@acerti.com.

const APPLY_CONTACT_EMAIL = "contact@acerti.com";

const ApplyField = ({ label, required, hint, children }) => (
  <label style={{ display: "block" }}>
    <span className="flbl">
      {label}{required && <span style={{ color: "var(--primary)" }}> *</span>}
    </span>
    {children}
    {hint && (
      <span style={{ display: "block", fontSize: 12, color: "var(--muted)", marginTop: 6 }}>
        {hint}
      </span>
    )}
  </label>
);

const ApplyModal = ({ open, onClose, role }) => {
  const [stage, setStage] = React.useState("form");
  const [form, setForm] = React.useState({ name: "", email: "", phone: "", cv: null });
  const [cvError, setCvError] = React.useState("");

  React.useEffect(() => {
    if (open) {
      setStage("form");
      setForm({ name: "", email: "", phone: "", cv: null });
      setCvError("");
    }
  }, [open, role]);

  if (!open || !role) return null;

  const roleLabel = `${role.code} — ${role.title}`;

  const onCvChange = (e) => {
    const f = e.target.files && e.target.files[0];
    setCvError("");
    if (!f) { setForm((s) => ({ ...s, cv: null })); return; }
    const okExt = /\.(pdf|docx?|rtf)$/i.test(f.name);
    const okMime = /pdf|word|officedocument|msword|rtf/i.test(f.type || "");
    if (!okExt && !okMime) {
      setCvError("Please upload a PDF or Word document (.pdf, .doc, .docx).");
      setForm((s) => ({ ...s, cv: null }));
      e.target.value = "";
      return;
    }
    if (f.size > 10 * 1024 * 1024) {
      setCvError("File is too large. Maximum size is 10 MB.");
      setForm((s) => ({ ...s, cv: null }));
      e.target.value = "";
      return;
    }
    setForm((s) => ({ ...s, cv: f }));
  };

  const onSubmit = (e) => {
    e.preventDefault();
    const subject = `Application — ${roleLabel} — ${form.name}`;
    const bodyLines = [
      `Role: ${roleLabel}`,
      `Engagement: Remote — LATAM · Full-time`,
      "",
      `Full Name:   ${form.name}`,
      `Email:       ${form.email}`,
      `Phone:       ${form.phone}`,
      `CV attached: ${form.cv ? form.cv.name + " (please attach manually before sending)" : "—"}`,
      "",
      "—",
      "Sent from acerti.com careers page",
    ];
    const url =
      "mailto:" + APPLY_CONTACT_EMAIL +
      "?subject=" + encodeURIComponent(subject) +
      "&body=" + encodeURIComponent(bodyLines.join("\n"));
    window.location.href = url;
    setStage("success");
  };

  return (
    <div
      onClick={onClose}
      style={{
        position: "fixed", inset: 0, zIndex: 100,
        background: "rgba(20,20,19,0.55)",
        backdropFilter: "blur(4px)",
        display: "flex", alignItems: "center", justifyContent: "center",
        padding: 24,
        animation: "modalFade 200ms var(--ease-standard)",
        overflowY: "auto",
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: "var(--canvas)", borderRadius: 16, padding: 40,
          width: "100%", maxWidth: 560, boxShadow: "var(--shadow-pop)",
          animation: "modalIn 260ms var(--ease-emphatic)",
          margin: "auto",
        }}
      >
        {stage === "form" ? (
          <>
            <div className="eyebrow" style={{ marginBottom: 14 }}><span className="mark"/>APPLY FOR THIS ROLE</div>
            <h3 className="display-md" style={{ marginBottom: 10 }}>{role.title}.</h3>
            <p style={{ fontSize: 14, color: "var(--muted)", marginBottom: 28 }}>
              We review every application within five business days. A senior
              recruiter &mdash; not an inbox bot &mdash; will reply.
            </p>
            <form onSubmit={onSubmit} style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              <ApplyField label="Full name" required>
                <input className="finput" required value={form.name}
                  onChange={(e) => setForm({ ...form, name: e.target.value })}
                  placeholder="Your full name" />
              </ApplyField>
              <ApplyField label="Email" required>
                <input className="finput" type="email" required value={form.email}
                  onChange={(e) => setForm({ ...form, email: e.target.value })}
                  placeholder="you@inbox.com" />
              </ApplyField>
              <ApplyField label="Phone number" required>
                <input className="finput" type="tel" required value={form.phone}
                  onChange={(e) => setForm({ ...form, phone: e.target.value })}
                  placeholder="+52 55 1234 5678" />
              </ApplyField>
              <ApplyField label="Role">
                <input className="finput finput-locked" value={roleLabel} readOnly disabled />
              </ApplyField>
              <ApplyField label="CV / Resume" required
                hint="PDF or Word document (.pdf, .doc, .docx) · max 10 MB">
                <div className="finput-file">
                  <label className="finput-file-btn">
                    <input type="file" accept=".pdf,.doc,.docx,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                      onChange={onCvChange} required />
                    <span>Choose file</span>
                  </label>
                  <span className="finput-file-name">
                    {form.cv ? form.cv.name : "No file selected"}
                  </span>
                </div>
                {cvError && (
                  <span style={{ display: "block", fontSize: 12, color: "var(--error)", marginTop: 6 }}>
                    {cvError}
                  </span>
                )}
              </ApplyField>

              <div style={{ display: "flex", gap: 10, marginTop: 6, justifyContent: "flex-end" }}>
                <button type="button" className="btn btn-secondary" onClick={onClose}>Cancel</button>
                <button type="submit" className="btn btn-primary">Submit application &rarr;</button>
              </div>
            </form>
          </>
        ) : (
          <div style={{ textAlign: "left" }}>
            <div className="eyebrow"><span className="mark"/>APPLICATION RECEIVED</div>
            <h3 className="display-md" style={{ marginTop: 14, marginBottom: 16 }}>
              Thank you, {form.name.split(" ")[0] || "friend"}.
            </h3>
            <p style={{ fontSize: 16, color: "var(--body)", marginBottom: 16 }}>
              Your email client should have opened with your application addressed to{" "}
              <a href={`mailto:${APPLY_CONTACT_EMAIL}`} style={{ color: "var(--primary)", fontWeight: 500 }}>
                {APPLY_CONTACT_EMAIL}
              </a>. Please <strong style={{ color: "var(--ink)" }}>attach your CV</strong> ({form.cv ? form.cv.name : "PDF or Word"}) and hit send.
            </p>
            <p style={{ fontSize: 14, color: "var(--muted)", marginBottom: 28 }}>
              Email clients can&rsquo;t auto-attach files from a web form for
              security reasons, so the file you selected needs to be dropped in
              manually. If your client didn&rsquo;t open, write to{" "}
              <a href={`mailto:${APPLY_CONTACT_EMAIL}`} style={{ color: "var(--ink)", fontWeight: 500 }}>
                {APPLY_CONTACT_EMAIL}
              </a> with the subject line shown above.
            </p>
            <button className="btn btn-primary" onClick={onClose}>Back to careers</button>
          </div>
        )}
      </div>
      <style>{`
        .finput {
          font-family: var(--font-body); font-size: 15px; color: var(--ink);
          background: var(--canvas); border: 1px solid var(--hairline);
          border-radius: 8px; padding: 10px 14px; outline: none; width: 100%;
        }
        .finput:focus { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(244,144,30,0.15); }
        .finput-locked {
          background: var(--surface-card); color: var(--muted);
          cursor: not-allowed; border-color: var(--hairline);
        }
        .flbl { font-size: 13px; font-weight: 500; color: var(--ink); margin-bottom: 6px; display: block; }
        .finput-file {
          display: flex; align-items: center; gap: 12px;
          background: var(--canvas); border: 1px dashed var(--hairline);
          border-radius: 8px; padding: 8px 10px 8px 8px;
        }
        .finput-file-btn {
          display: inline-flex; align-items: center; gap: 6px;
          background: var(--ink); color: var(--on-dark);
          padding: 8px 14px; border-radius: 6px;
          font-size: 13px; font-weight: 500; cursor: pointer;
          white-space: nowrap;
          transition: background var(--duration-fast) var(--ease-standard);
        }
        .finput-file-btn:hover { background: var(--primary); color: var(--on-primary); }
        .finput-file-btn input[type="file"] { display: none; }
        .finput-file-name {
          font-size: 13px; color: var(--muted);
          white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
        }
        @keyframes modalFade { from { opacity: 0; } to { opacity: 1; } }
        @keyframes modalIn { from { opacity: 0; transform: translateY(12px) scale(0.98); } to { opacity: 1; transform: none; } }
      `}</style>
    </div>
  );
};

Object.assign(window, { ApplyModal });
