function BookingModal({ open, onClose }) {
  const [sent, setSent] = React.useState(false);
  const [status, setStatus] = React.useState("idle"); // idle | sending | error
  const [error, setError] = React.useState("");
  React.useEffect(() => { if (open) { setSent(false); setStatus("idle"); setError(""); } }, [open]);

  const submit = async (event) => {
    event.preventDefault();
    if (status === "sending") return;
    const form = event.currentTarget;
    const data = Object.fromEntries(new FormData(form).entries());
    data.source = "booking";
    setStatus("sending");
    setError("");
    try {
      const res = await fetch("/api/lead", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify(data),
      });
      const result = await res.json().catch(() => ({}));
      if (res.ok && result.ok) {
        setSent(true);
        setStatus("idle");
      } else {
        setStatus("error");
        setError(result.error || "Something went wrong. Please try again.");
      }
    } catch {
      setStatus("error");
      setError("We couldn't reach the server. Please check your connection and try again.");
    }
  };

  React.useEffect(() => {
    if (!open) return;
    const onKey = (event) => {
      if (event.key === "Escape") onClose();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, zIndex: 100, background: "rgba(31,40,50,0.45)",
      backdropFilter: "blur(3px)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20,
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: "var(--surface-card)", borderRadius: "var(--radius-xl)", boxShadow: "var(--shadow-xl)",
        width: "100%", maxWidth: 460, padding: 30, position: "relative",
      }}>
        <div style={{ position: "absolute", top: 16, right: 16 }}>
          <IconButton label="Close" onClick={onClose}><Icon name="x" size={20} /></IconButton>
        </div>
        {sent ? (
          <div style={{ textAlign: "center", padding: "20px 0" }}>
            <span style={{ width: 60, height: 60, borderRadius: "50%", background: "var(--sage-100)", color: "var(--sage-600)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
              <Icon name="check" size={30} stroke={2.4} />
            </span>
            <h3 style={{ fontSize: 23, margin: "16px 0 6px" }}>Request received!</h3>
            <p style={{ color: "var(--text-muted)", margin: "0 0 22px" }}>We'll call within one business day to find a time that works for your family.</p>
            <Button variant="primary" block onClick={onClose}>Done</Button>
          </div>
        ) : (
          <form onSubmit={submit} noValidate>
            <img src="../../assets/logomark.svg" width="40" height="40" alt="" />
            <h3 style={{ fontSize: 24, margin: "10px 0 4px" }}>Book a free consult</h3>
            <p style={{ color: "var(--text-muted)", margin: "0 0 20px", fontSize: 15 }}>A 30-minute call with our care team. No referral needed.</p>
            <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              <Input label="Your name" name="name" required placeholder="Jordan Rivera" />
              <Input label="Email" name="email" type="email" required placeholder="you@example.com" />
              <Select label="Area of interest" name="interest" defaultValue="st" options={[
                { value: "st", label: "Speech therapy" },
                { value: "ot", label: "Occupational therapy" },
                { value: "pt", label: "Physical therapy" },
                { value: "ns", label: "Not sure yet, help me decide" },
              ]} />
              <input type="text" name="company" tabIndex={-1} autoComplete="off" aria-hidden="true" style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0 }} />
              {status === "error" && (
                <p role="alert" style={{ margin: 0, color: "var(--rose-600, #c0405b)", fontSize: 14 }}>{error}</p>
              )}
              <Button type="submit" variant="primary" size="lg" block disabled={status === "sending"} style={{ marginTop: 4 }}>
                {status === "sending" ? "Sending…" : "Request my consult"}
              </Button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}
window.BookingModal = BookingModal;
