/* CtaModal — one accessible contact modal with four entry points.
   Opens when any element with a matching data-cta is clicked:
     book-scan · request-pricing · talk-to-team · contact
   Heading, button label, focus target and the hidden `intent` value change
   per entry point; everything else is shared. Submits to hello@aai-labs.com
   with an intent-specific subject, then swaps to a confirmation panel.

   Accessibility: role=dialog + aria-modal, labelled/described, focus trap,
   ESC + click-outside to close, focus returns to the opener, real <label>s,
   honeypot for spam. */
const { Button } = window.AIScanDesignSystem_81b9d1;
const CarbonIcon = window.CarbonIcon;

/* The privacy link points at the clean URL (/privacy-policy); Cloudflare
   Pages serves it from privacy-policy.html. */
const CTA_INTENTS = {
  "book-scan": {
    intent: "book-scan",
    title: "Book a scan",
    sub: "Tell us a little about your company and we'll be in touch.",
    submit: "Book my scan",
    subject: "AI Scan — Book a scan request",
    focus: "name",
  },
  "request-pricing": {
    intent: "request-pricing",
    title: "Request pricing",
    sub: "Tell us a little about your company and we'll send pricing.",
    submit: "Request pricing",
    subject: "AI Scan — Pricing request",
    focus: "name",
  },
  "talk-to-team": {
    intent: "general",
    title: "Get in touch",
    sub: "Send us a note and we'll get back to you.",
    submit: "Send message",
    subject: "AI Scan — General enquiry",
    focus: "message",
  },
};
CTA_INTENTS["contact"] = { ...CTA_INTENTS["talk-to-team"], subject: "AI Scan — Contact enquiry" };

const FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])';

function CtaModal() {
  const [mounted, setMounted] = React.useState(false); // present in DOM (for exit anim)
  const [shown, setShown] = React.useState(false);     // .is-open (opacity)
  const [cfg, setCfg] = React.useState(null);
  const [submitted, setSubmitted] = React.useState(false);

  const openerRef = React.useRef(null);
  const overlayRef = React.useRef(null);
  const dialogRef = React.useRef(null);
  const successRef = React.useRef(null);
  const closeTimer = React.useRef(null);

  const titleId = React.useId();
  const subId = React.useId();

  /* Delegated open: any [data-cta] whose value maps to an intent. */
  React.useEffect(() => {
    function onClick(e) {
      const trigger = e.target.closest("[data-cta]");
      if (!trigger) return;
      const conf = CTA_INTENTS[trigger.getAttribute("data-cta")];
      if (!conf) return;
      e.preventDefault();
      openerRef.current = trigger;
      clearTimeout(closeTimer.current);
      setSubmitted(false);
      setCfg(conf);
      setMounted(true);
    }
    document.addEventListener("click", onClick);
    return () => document.removeEventListener("click", onClick);
  }, []);

  /* Drive the open transition: once mounted, flip `shown` on the next frame so
     the CSS opacity/transform transition runs. */
  React.useEffect(() => {
    if (!mounted) { setShown(false); return; }
    const id = requestAnimationFrame(() => setShown(true));
    return () => cancelAnimationFrame(id);
  }, [mounted]);

  const close = React.useCallback(() => {
    setShown(false);
    const opener = openerRef.current;
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    closeTimer.current = setTimeout(() => {
      setMounted(false);
      if (opener) opener.focus();
    }, reduce ? 0 : 190);
  }, []);

  /* While open: lock scroll, ESC to close, trap Tab. */
  React.useEffect(() => {
    if (!mounted) return;
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    function onKey(e) {
      if (e.key === "Escape") { e.preventDefault(); close(); return; }
      if (e.key !== "Tab") return;
      const dlg = dialogRef.current;
      if (!dlg) return;
      const items = [...dlg.querySelectorAll(FOCUSABLE)].filter((el) => el.offsetParent !== null);
      if (!items.length) return;
      const first = items[0], last = items[items.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);
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [mounted, close]);

  /* Field focus on open is handled by native autoFocus (reliable on each
     remount). This effect only moves focus to the confirmation on submit. */
  React.useEffect(() => {
    if (!mounted || !submitted) return;
    const t = setTimeout(() => { successRef.current && successRef.current.focus(); }, 40);
    return () => clearTimeout(t);
  }, [mounted, submitted]);

  function onSubmit(e) {
    e.preventDefault();
    const form = e.currentTarget;
    if (form.elements.company_url && form.elements.company_url.value) { setSubmitted(true); return; } // honeypot
    if (!form.checkValidity()) { form.reportValidity(); return; }
    const d = new FormData(form);
    const body = [
      "Intent: " + cfg.intent,
      "Name: " + (d.get("name") || ""),
      "Work email: " + (d.get("email") || ""),
      "Company: " + (d.get("company") || ""),
      "Company size: " + (d.get("company_size") || "—"),
      "",
      (d.get("message") || ""),
    ].join("\n");
    /* Open the pre-filled mail draft without navigating the page away. */
    const a = document.createElement("a");
    a.href = "mailto:hello@aai-labs.com?subject=" + encodeURIComponent(cfg.subject) + "&body=" + encodeURIComponent(body);
    a.style.display = "none";
    document.body.appendChild(a);
    a.click();
    a.remove();
    setSubmitted(true);
  }

  if (!mounted || !cfg) return null;

  return (
    <div
      ref={overlayRef}
      className={"ls-modal-overlay" + (shown ? " is-open" : "")}
      onMouseDown={(e) => { if (e.target === overlayRef.current) close(); }}
    >
      <div
        ref={dialogRef}
        className="ls-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby={titleId}
        aria-describedby={submitted ? undefined : subId}
      >
        <div className="ls-modal__head">
          <h2 id={titleId} className="ls-modal__title">{cfg.title}</h2>
          <button type="button" className="ls-modal__close" aria-label="Close dialog" onClick={close}>
            <CarbonIcon name="close" />
          </button>
        </div>

        {submitted ? (
          <div className="ls-modal__success" ref={successRef} tabIndex={-1}>
            <span className="ls-modal__successicon" aria-hidden="true"><CarbonIcon name="checkmark" /></span>
            <p className="ls-modal__successtitle">Thank you! We'll be in touch.</p>
            <div className="ls-modal__successbtn">
              <Button variant="secondary" onClick={close}>Close</Button>
            </div>
          </div>
        ) : (
          <React.Fragment>
            <p id={subId} className="ls-modal__sub">{cfg.sub}</p>
            <form className="ls-modal__form" onSubmit={onSubmit} noValidate={false}>
              <input type="hidden" name="intent" value={cfg.intent} />

              {/* Honeypot — hidden from people & AT; bots that fill it are dropped. */}
              <div className="ls-hp" aria-hidden="true">
                <label htmlFor="company_url">Company URL (leave blank)</label>
                <input id="company_url" name="company_url" type="text" tabIndex={-1} autoComplete="off" />
              </div>

              <label className="ls-field">
                <span className="ls-field__label">Full name <span className="ls-field__req" aria-hidden="true">*</span><span className="ls-sr-only">(required)</span></span>
                <input className="ls-field__control" name="name" type="text" required autoComplete="name" autoFocus={cfg.focus === "name"} placeholder="Jane Smith" />
              </label>

              <label className="ls-field">
                <span className="ls-field__label">Work email <span className="ls-field__req" aria-hidden="true">*</span><span className="ls-sr-only">(required)</span></span>
                <input className="ls-field__control" name="email" type="email" required autoComplete="email" inputMode="email" placeholder="jane@company.com" />
              </label>

              <label className="ls-field">
                <span className="ls-field__label">Company <span className="ls-field__req" aria-hidden="true">*</span><span className="ls-sr-only">(required)</span></span>
                <input className="ls-field__control" name="company" type="text" required autoComplete="organization" placeholder="Company name" />
              </label>

              <label className="ls-field">
                <span className="ls-field__label">Company size</span>
                <select className="ls-field__control" name="company_size" defaultValue="">
                  <option value="" disabled>Select a range</option>
                  <option value="1–49">1–49</option>
                  <option value="50–200">50–200</option>
                  <option value="201–500">201–500</option>
                  <option value="500+">500+</option>
                </select>
              </label>

              <label className="ls-field">
                <span className="ls-field__label">Anything you'd like us to know?</span>
                <textarea className="ls-field__control" name="message" rows={3} autoFocus={cfg.focus === "message"} placeholder="Optional"></textarea>
              </label>

              <Button type="submit" variant="primary" size="lg" className="aisn-btn--scan ls-modal__submit">{cfg.submit}</Button>

              <p className="ls-modal__privacy">
                By submitting, you agree to our <a href="/privacy-policy">Privacy Policy</a>. We'll only use your details to respond.
              </p>
            </form>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}
window.CtaModal = CtaModal;
