/* Dr Jillian - Black Friday open day: privacy policy lightbox, opened by any privacy-policy link (footer and ActiveCampaign form) */
(function () {
  const { useEffect, useRef } = React;
  const EMAIL = "enquiries@drjillian.co.uk";

  // Turns the practice email address into a mailto link
  const withEmail = (t) => t.split(EMAIL).flatMap((part, i) => i ? [<a key={i} href={"mailto:" + EMAIL}>{EMAIL}</a>, part] : [part]);

  function PrivacyLightbox() {
    const dlg = useRef(null);
    useEffect(() => {
      // Capture phase, so the ActiveCampaign link is caught before the embed sees it
      const onClick = (e) => {
        const a = e.target.closest && e.target.closest("a[href*='privacy-policy']");
        if (!a || e.metaKey || e.ctrlKey || e.shiftKey) return;
        e.preventDefault();
        e.stopPropagation();
        dlg.current.showModal();
        dlg.current.querySelector(".pp__body").scrollTop = 0;
      };
      document.addEventListener("click", onClick, true);
      return () => document.removeEventListener("click", onClick, true);
    }, []);
    const close = () => dlg.current.close();
    return (
      <dialog className="pp" ref={dlg} aria-labelledby="pp-h" onClick={(e) => { if (e.target === dlg.current) close(); }}>
        <div className="pp__head">
          <h2 className="h3" id="pp-h">Privacy policy</h2>
          <button className="pp__x" type="button" onClick={close} aria-label="Close privacy policy"><window.DjIc n="plus" /></button>
        </div>
        <div className="pp__body">
          {(window.DjPrivacy || []).map(([t, text], i) => {
            const Tag = t;
            return <Tag key={i}>{withEmail(text)}</Tag>;
          })}
        </div>
      </dialog>
    );
  }

  const mount = document.createElement("div");
  document.body.appendChild(mount);
  ReactDOM.createRoot(mount).render(<PrivacyLightbox />);
})();
