// Get Started Modal — opens on any "Get Started" CTA. Captures name, email,
// phone, and investment range. Listens for window event "open-get-started" so
// any button anywhere can trigger it: window.dispatchEvent(new CustomEvent(...)).
// Form submissions are forwarded as email via FormSubmit (no backend needed).
// First submission triggers a one-time activation email to this address.
const LEAD_INBOX = "Ibukun@userank.com";

function GetStartedModal({ modalImg = "assets/images/advisor.jpg" }) {
  const [open, setOpen] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState("");
  const [form, setForm] = React.useState({ name: "", email: "", phone: "", range: "" });

  // Track the element that opened the modal so we can return focus on close.
  const triggerRef = React.useRef(null);
  const cardRef = React.useRef(null);
  const firstFieldRef = React.useRef(null);
  const headingId = "get-started-heading";

  const close = () => { if (!sending) setOpen(false); };

  // Listen for the global open event from any CTA.
  React.useEffect(() => {
    const onOpen = () => {
      triggerRef.current = document.activeElement;
      setSubmitted(false);
      setError("");
      setSending(false);
      setForm({ name: "", email: "", phone: "", range: "" });
      setOpen(true);
    };
    window.addEventListener("open-get-started", onOpen);
    return () => window.removeEventListener("open-get-started", onOpen);
  }, []);

  // While open: lock scroll, listen for Esc, focus-trap Tab, move initial focus
  // into the dialog. On close, restore focus to whatever opened it.
  React.useEffect(() => {
    if (!open) return;
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";

    // Focus the first form field after the modal mounts.
    requestAnimationFrame(() => firstFieldRef.current?.focus());

    const focusables = () => {
      const card = cardRef.current;
      if (!card) return [];
      return Array.from(
        card.querySelectorAll(
          'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'
        )
      ).filter(el => !el.hasAttribute("aria-hidden") && el.offsetParent !== null);
    };

    const onKey = (e) => {
      if (e.key === "Escape") { close(); return; }
      if (e.key !== "Tab") return;
      // Focus trap — wrap Tab/Shift+Tab between first and last focusable.
      const list = focusables();
      if (list.length === 0) return;
      const first = list[0];
      const 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();
      }
    };

    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = prevOverflow;
      window.removeEventListener("keydown", onKey);
      // Restore focus to the trigger element (if it still exists in the DOM).
      const trigger = triggerRef.current;
      if (trigger && document.body.contains(trigger)) trigger.focus();
    };
  }, [open]);

  if (!open) return null;

  const set = (k) => (e) => setForm(prev => ({ ...prev, [k]: e.target.value }));

  // FormSubmit.co JSON endpoint — no signup, no key. Forwards the form fields
  // as an email to LEAD_INBOX. _replyto lets the recipient reply straight to
  // the prospect; _subject sets the email subject; _captcha:false skips
  // hCaptcha for AJAX (we trust the modal-only entry path).
  const submit = async (e) => {
    e.preventDefault();
    setSending(true);
    setError("");
    try {
      const res = await fetch(
        "https://formsubmit.co/ajax/" + encodeURIComponent(LEAD_INBOX),
        {
          method: "POST",
          headers: { "Content-Type": "application/json", Accept: "application/json" },
          body: JSON.stringify({
            _subject: "New Get Started lead — Rank Asset Managers",
            _template: "table",
            _captcha: "false",
            _replyto: form.email,
            Name: form.name,
            Email: form.email,
            Phone: form.phone,
            "Investment range": form.range,
          }),
        }
      );
      const data = await res.json().catch(() => ({}));
      if (!res.ok || data.success === "false") {
        throw new Error(data.message || "Network error");
      }
      setSubmitted(true);
    } catch (err) {
      setError("We couldn't send your message. Please try again or email " + LEAD_INBOX + " directly.");
    } finally {
      setSending(false);
    }
  };

  const ranges = [
    "Under ₦1M",
    "₦1M – ₦5M",
    "₦5M – ₦25M",
    "₦25M – ₦100M",
    "Over ₦100M",
  ];

  return (
    <div className="modal-overlay" onClick={close} role="dialog" aria-modal="true" aria-labelledby={headingId}>
      <div className="modal-card" onClick={(e) => e.stopPropagation()} ref={cardRef}>
        <button className="modal-close" onClick={close} aria-label="Close dialog" type="button">
          <svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true" focusable="false">
            <path d="M1 1 L13 13 M13 1 L1 13" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>
          </svg>
        </button>

        <div className="modal-media" aria-hidden="true">
          <img src={modalImg} alt="" loading="lazy" decoding="async"/>
        </div>

        <div className="modal-body">
          {submitted ? (
            <div className="modal-thanks">
              <h3 id={headingId}>Thanks — we&apos;ll be in touch.</h3>
              <p>An advisor will reach out within one business day.</p>
              <button className="btn btn-primary" onClick={close} type="button">Close</button>
            </div>
          ) : (
            <form className="modal-form" onSubmit={submit} noValidate>
              <h3 id={headingId}>Let&apos;s get started.</h3>
              <p className="modal-sub">Tell us a little about you — an advisor will follow up.</p>

              <label className="modal-field">
                <span>Full name</span>
                <input ref={firstFieldRef} type="text" required value={form.name} onChange={set("name")} autoComplete="name"/>
              </label>
              <label className="modal-field">
                <span>Email</span>
                <input type="email" required value={form.email} onChange={set("email")} autoComplete="email"/>
              </label>
              <label className="modal-field">
                <span>Phone number</span>
                <input type="tel" required value={form.phone} onChange={set("phone")} autoComplete="tel"/>
              </label>
              <label className="modal-field">
                <span>Investment range</span>
                <select required value={form.range} onChange={set("range")}>
                  <option value="" disabled>Select a range…</option>
                  {ranges.map(r => <option key={r} value={r}>{r}</option>)}
                </select>
              </label>

              {error && <div className="modal-error" role="alert">{error}</div>}

              <button type="submit" className="btn btn-primary modal-submit" disabled={sending}>
                {sending ? "Sending…" : "Get Started"}
              </button>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}
window.GetStartedModal = GetStartedModal;
