// Inline "Talk to sales" form — POSTs to /api/enterprise-contact which
// upserts a Person in Attio and attaches a Note with the submission context.
// See apps/marketing-site/backend/app/main.py for the backend flow.

function ContactForm() {
  const [values, setValues] = React.useState({
    name: "",
    email: "",
    company: "",
    role: "",
    message: "",
  });
  const [status, setStatus] = React.useState("idle");
  // "idle" | "submitting" | "success" | "error"
  const [error, setError] = React.useState(null);

  const bind = (field) => ({
    value: values[field],
    onChange: (e) =>
      setValues((v) => ({ ...v, [field]: e.target.value })),
    disabled: status === "submitting",
  });

  const submit = async (e) => {
    e.preventDefault();
    if (status === "submitting") return;
    setStatus("submitting");
    setError(null);
    try {
      const res = await fetch("/api/enterprise-contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(values),
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok) {
        setStatus("success");
        // Fire a PostHog event on successful submission. Email lets us
        // link the lead back to the Attio Person; the other fields are
        // useful context on PostHog dashboards. PostHog may not be
        // loaded in some environments (e.g. local without the snippet),
        // so guard on window.posthog.
        if (typeof window !== "undefined" && window.posthog) {
          window.posthog.capture("enterprise_contact_submitted", {
            email: values.email,
            company: values.company,
            has_role: Boolean(values.role),
            has_message: Boolean(values.message),
          });
        }
      } else {
        setStatus("error");
        setError(data.error || "Something went wrong. Please try again.");
      }
    } catch (_err) {
      setStatus("error");
      setError("Network error — please try again.");
    }
  };

  if (status === "success") {
    return (
      <div className="contact-form contact-form--success" role="status">
        <h4 className="contact-form__title">Got it</h4>
        <p className="contact-form__success-body">
          Thanks — we'll be in touch within a business day.
        </p>
        <p className="contact-form__success-meta">
          In the meantime, poke around the{" "}
          <a href="https://playground.atopile.io" target="_blank" rel="noopener noreferrer">
            playground
          </a>{" "}
          or the{" "}
          <a href="https://docs.atopile.io" target="_blank" rel="noopener noreferrer">
            docs
          </a>
          .
        </p>
      </div>
    );
  }

  const submitting = status === "submitting";

  return (
    <form className="contact-form" onSubmit={submit} noValidate>
      <h4 className="contact-form__title">Talk to sales</h4>

      <div className="contact-form__row">
        <label className="contact-form__field">
          <span>Full name</span>
          <input
            type="text"
            required
            maxLength={200}
            autoComplete="name"
            {...bind("name")}
          />
        </label>
        <label className="contact-form__field">
          <span>Corporate email</span>
          <input
            type="email"
            required
            maxLength={320}
            autoComplete="email"
            {...bind("email")}
          />
        </label>
      </div>

      <div className="contact-form__row">
        <label className="contact-form__field">
          <span>Company</span>
          <input
            type="text"
            required
            maxLength={200}
            autoComplete="organization"
            {...bind("company")}
          />
        </label>
        <label className="contact-form__field">
          <span>
            Role <em>optional</em>
          </span>
          <input
            type="text"
            maxLength={200}
            autoComplete="organization-title"
            {...bind("role")}
          />
        </label>
      </div>

      <label className="contact-form__field">
        <span>
          What are you trying to do? <em>optional</em>
        </span>
        <textarea rows={3} maxLength={5000} {...bind("message")} />
      </label>

      {error && (
        <div className="contact-form__error" role="alert">
          {error}
        </div>
      )}

      <button
        type="submit"
        className="btn btn--primary contact-form__submit"
        disabled={submitting}
      >
        {submitting ? "Sending…" : "Request demo →"}
      </button>
    </form>
  );
}

window.ContactForm = ContactForm;
