const { Input, Select, Button } = window.NRTRDesignSystem_47db9c;

// ── Founding-list form endpoint ───────────────────────────────────────────
// Formspree (https://formspree.io) endpoint receiving founding-list signups.
// Swap the ID to point at a different form.
const FOUNDING_LIST_ENDPOINT = "https://formspree.io/f/xgojpkkv";

function BookingModal({ open, onClose, defaultInterest }) {
  const [sent, setSent] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [name, setName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [interest, setInterest] = React.useState(defaultInterest || "Physical Therapy");
  const [submitError, setSubmitError] = React.useState("");
  const [touched, setTouched] = React.useState({});
  const dialogRef = React.useRef(null);
  const triggerRef = React.useRef(null);

  const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
  const nameOk = name.trim().length > 1;
  const errors = {
    name: touched.name && !nameOk ? "Please enter your name." : undefined,
    email: touched.email && !emailOk ? "Enter a valid email address." : undefined,
  };

  React.useEffect(() => {
    if (open) {
      setSent(false);
      setSubmitting(false);
      setSubmitError("");
      setTouched({});
      if (defaultInterest) setInterest(defaultInterest);
      triggerRef.current = document.activeElement;
      const t = setTimeout(() => {
        if (dialogRef.current) {
          const el = dialogRef.current.querySelector("input, select, textarea");
          if (el) el.focus();
        }
      }, 60);
      return () => clearTimeout(t);
    } else if (triggerRef.current && triggerRef.current.focus) {
      triggerRef.current.focus();
    }
  }, [open, defaultInterest]);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === "Escape") { onClose(); return; }
      if (e.key === "Tab" && dialogRef.current) {
        const f = dialogRef.current.querySelectorAll(
          'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
        );
        const list = Array.prototype.filter.call(f, (el) => !el.disabled && el.offsetParent !== null);
        if (!list.length) return;
        const first = list[0], last = list[list.length - 1];
        if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
        else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
      }
    };
    document.addEventListener("keydown", onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = prev;
    };
  }, [open, onClose]);

  if (!open) return null;

  const submit = async () => {
    setTouched({ name: true, email: true });
    if (!nameOk || !emailOk) return;
    setSubmitting(true);
    setSubmitError("");
    const payload = { name: name.trim(), email: email.trim(), interest, source: "founding-list" };
    try {
      const res = await fetch(FOUNDING_LIST_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify(payload),
      });
      if (!res.ok) throw new Error("Request failed");
      setSubmitting(false);
      setSent(true);
    } catch (err) {
      setSubmitting(false);
      setSubmitError("Something went wrong. Please try again, or email us at jacob@nrtr.life.");
    }
  };

  const perks = [
    ["Founding rates", "Locked for your first full year."],
    ["Five guest passes a month", "To share the space you found."],
  ];

  return (
    <div
      onClick={onClose}
      style={{
        position: "fixed", inset: 0, zIndex: 100,
        background: "rgba(32,24,15,0.72)",
        display: "flex", alignItems: "center", justifyContent: "center", padding: "20px",
        animation: "nrtrOverlayIn 220ms ease",
      }}
    >
      <div
        ref={dialogRef}
        role="dialog"
        aria-modal="true"
        aria-labelledby="fl-modal-title"
        onClick={(e) => e.stopPropagation()}
        style={{
          width: "min(480px, 100%)", maxHeight: "90vh", overflowY: "auto", background: "var(--surface-raised)",
          borderRadius: "var(--radius-xl)", boxShadow: "var(--shadow-lg)",
          border: "1px solid var(--line-soft)", padding: "clamp(24px, 6vw, 48px)",
          animation: "nrtrModalIn 320ms cubic-bezier(.16,1,.3,1)",
        }}
      >
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
          <div>
            <div style={{ fontFamily: "var(--font-label)", fontSize: "11px", letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--text-brand)", marginBottom: "8px" }}>Founding List</div>
            <h3 id="fl-modal-title" style={{ margin: 0, fontSize: "26px" }}>Register your interest</h3>
          </div>
          <button onClick={onClose} aria-label="Close" style={{ border: "none", background: "none", fontSize: "20px", cursor: "pointer", color: "var(--text-muted)", lineHeight: 1 }}>✕</button>
        </div>

        {sent ? (
          <div style={{ padding: "28px 0 8px", textAlign: "center" }}>
            <img src="assets/icons/mark-primary-terracotta.svg" alt="" style={{ width: 56, height: 56, marginBottom: "16px" }} />
            <p style={{ fontFamily: "var(--font-body)", fontSize: "18px", color: "var(--text-strong)", margin: "0 0 6px" }}>You're on the list.</p>
            <p style={{ color: "var(--text-muted)", margin: "0 auto", maxWidth: "40ch", lineHeight: 1.55 }}>We'll mark your interest and keep you updated on our opening timeline.</p>
            <div style={{ marginTop: "24px" }}>
              <Button variant="primary" size="lg" onClick={onClose}>Done</Button>
            </div>
          </div>
        ) : (
          <React.Fragment>
            <div style={{ display: "flex", flexDirection: "column", gap: "10px", margin: "20px 0 6px" }}>
              {perks.map(([t, d]) => (
                <div key={t} style={{ display: "flex", alignItems: "baseline", gap: "10px" }}>
                  <span aria-hidden="true" style={{ flexShrink: 0, width: 6, height: 6, borderRadius: "50%", background: "var(--terracotta)", transform: "translateY(-2px)" }} />
                  <span style={{ fontFamily: "var(--font-body)", fontSize: "14.5px", lineHeight: 1.45, color: "var(--text-body)" }}>
                    <strong style={{ fontWeight: 500, color: "var(--text-strong)" }}>{t}</strong> — {d}
                  </span>
                </div>
              ))}
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: "16px", marginTop: "18px" }}>
              <Input
                label="Full Name"
                placeholder="Jordan Rivera"
                value={name}
                onChange={(e) => setName(e.target.value)}
                error={errors.name}
                required
                autoComplete="name"
              />
              <Input
                label="Email"
                type="email"
                placeholder="you@example.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                error={errors.email}
                required
                autoComplete="email"
              />
              <Select label="What are you most interested in?" options={["Physical Therapy", "Contrast Suite", "Membership", "Biometric Testing", "Not sure yet"]} value={interest} onChange={(e) => setInterest(e.target.value)} />
              {submitError && (
                <p role="alert" style={{ fontFamily: "var(--font-body)", fontSize: "14px", lineHeight: 1.5, color: "var(--terracotta)", margin: 0 }}>{submitError}</p>
              )}
              <Button variant="primary" size="lg" fullWidth disabled={submitting} onClick={submit} style={{ marginTop: "6px" }}>
                {submitting ? "Joining…" : "Join the Founding List"}
              </Button>
              <p style={{ fontFamily: "var(--font-body)", fontSize: "12.5px", lineHeight: 1.5, color: "var(--text-muted)", textAlign: "center", margin: "2px 0 0" }}>
                No payment today. Founding rates are locked for your first year — we'll only reach out as we approach opening.
              </p>
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

window.BookingModal = BookingModal;
