// ContactModal.jsx — slide-in contact modal

const Field = ({ label, required, children }) => (
  <label style={{ display: "block" }}>
    <span className="flbl">
      {label}{required && <span style={{ color: "var(--primary)" }}> *</span>}
    </span>
    {children}
  </label>
);

// Recipient for contact form submissions. Update here to change everywhere.
const CONTACT_EMAIL = "contact@acerti.com";

// Builds a mailto: fallback URL from the form (used only if the API call fails).
const buildMailto = (form) => {
  const subjectBits = [form.name, form.interest].filter(Boolean).join(" \u2014 ");
  const subject = "New acerti inquiry" + (subjectBits ? ": " + subjectBits : "");
  const body = [
    "Name: " + (form.name || "—"),
    "Email: " + (form.email || "—"),
    "Company: " + (form.company || "—"),
    "Interested in: " + (form.interest || "—"),
    "",
    "Project notes:",
    form.notes || "—",
    "",
    "—",
    "Sent from acerti.com contact form",
  ].join("\n");
  return "mailto:" + CONTACT_EMAIL +
    "?subject=" + encodeURIComponent(subject) +
    "&body=" + encodeURIComponent(body);
};

const ContactModal = ({ open, onClose, prefill }) => {
  const [stage, setStage] = React.useState("form"); // "form" | "success"
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState("");
  const [form, setForm] = React.useState({
    name: "", email: "", company: "", interest: prefill || "", notes: "",
  });
  React.useEffect(() => {
    if (open) {
      setStage("form"); setError(""); setSubmitting(false);
      setForm((f) => ({ ...f, interest: prefill || f.interest }));
    }
  }, [open, prefill]);
  if (!open) return null;

  const onSubmit = async (e) => {
    e.preventDefault();
    if (submitting) return;
    setSubmitting(true);
    setError("");
    try {
      // Submit to the Vercel serverless function, which sends the email
      // server-side via Resend — no mail client needed.
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      if (!res.ok) {
        let msg = "We couldn't send your message. Please try again, or email us directly.";
        try { const j = await res.json(); if (j && j.error) msg = j.error; } catch (_) {}
        throw new Error(msg);
      }
      setStage("success");
    } catch (err) {
      setError(err.message || "Something went wrong. Please email us directly.");
    } finally {
      setSubmitting(false);
    }
  };

  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)",
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: "var(--canvas)", borderRadius: 16, padding: 40,
          width: "100%", maxWidth: 520, boxShadow: "var(--shadow-pop)",
          animation: "modalIn 260ms var(--ease-emphatic)",
        }}
      >
        {stage === "form" ? (
          <>
            <div className="eyebrow" style={{ marginBottom: 14 }}><span className="mark"/>START A CONVERSATION</div>
            <h3 className="display-md" style={{ marginBottom: 10 }}>Tell us what you're building.</h3>
            <p style={{ fontSize: 14, color: "var(--muted)", marginBottom: 28 }}>
              A senior consultant &mdash; not a sales rep &mdash; will reply within
              one business day.
            </p>
            <form onSubmit={onSubmit} style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              <Field label="Name" required>
                <input className="finput" required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="Your full name" />
              </Field>
              <Field label="Work email" required>
                <input className="finput" type="email" required value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} placeholder="you@company.com" />
              </Field>
              <Field label="Company">
                <input className="finput" value={form.company} onChange={(e) => setForm({ ...form, company: e.target.value })} placeholder="Company or project name" />
              </Field>
              <Field label="Interested in">
                <select className="finput" value={form.interest} onChange={(e) => setForm({ ...form, interest: e.target.value })}>
                  <option value="">Select a model or service</option>
                  <option>Project-Based</option>
                  <option>Managed Teams</option>
                  <option>Staff Augmentation</option>
                  <option>SAP / ERP consulting</option>
                  <option>AI Voice / Call Center</option>
                  <option>Software Development</option>
                  <option>Other / not sure</option>
                </select>
              </Field>
              <Field label="A line or two on the project">
                <textarea className="finput" rows={3} value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} placeholder="Stack, timeline, what you're hoping to achieve." />
              </Field>
              {error && (
                <div style={{ fontSize: 13, color: "#b3401a", background: "rgba(179,64,26,0.08)", border: "1px solid rgba(179,64,26,0.2)", borderRadius: 8, padding: "10px 14px", lineHeight: 1.5 }}>
                  {error}{" "}
                  <a href={buildMailto(form)} style={{ color: "var(--ink)", fontWeight: 500 }}>Email us instead &rarr;</a>
                </div>
              )}
              <div style={{ display: "flex", gap: 10, marginTop: 6, justifyContent: "flex-end" }}>
                <button type="button" className="btn btn-secondary" onClick={onClose} disabled={submitting}>Cancel</button>
                <button type="submit" className="btn btn-primary" disabled={submitting}>
                  {submitting ? "Sending\u2026" : <>Send &rarr;</>}
                </button>
              </div>
            </form>
          </>
        ) : (
          <div style={{ textAlign: "left" }}>
            <div className="eyebrow"><span className="mark"/>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 message is on its way to our team. We&rsquo;ve sent it to{" "}
              <a href={`mailto:${CONTACT_EMAIL}`} style={{ color: "var(--primary)", fontWeight: 500 }}>
                {CONTACT_EMAIL}
              </a>.
            </p>
            <p style={{ fontSize: 14, color: "var(--muted)", marginBottom: 28 }}>
              A senior consultant &mdash; not a sales rep &mdash; will reply within one
              business day. If anything&rsquo;s urgent, you can also write us
              directly at{" "}
              <a href={`mailto:${CONTACT_EMAIL}`} style={{ color: "var(--ink)", fontWeight: 500 }}>
                {CONTACT_EMAIL}
              </a>.
            </p>
            <button className="btn btn-primary" onClick={onClose}>Back to acerti.com</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); }
        .flbl { font-size: 13px; font-weight: 500; color: var(--ink); margin-bottom: 6px; display: block; }
        @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, { ContactModal });
