// Full-viewport Tally embed: data-tally-src + embed.js + Tally.loadEmbeds() (see Tally docs).
// Embed URL comes from Sanity `siteSettings.requestAccess.primaryCtaUrl` (via `amos-site-context.js`), with sane defaults.

function WaitlistModal({ open, onClose }) {
  const prevOverflowRef = React.useRef("");
  const tallySrc = React.useMemo(() => {
    if (typeof window !== "undefined" && typeof window.__AMOS_TALLY_EMBED_SRC__ === "function") {
      return window.__AMOS_TALLY_EMBED_SRC__();
    }
    if (typeof window !== "undefined" && typeof window.__AMOS_DEFAULT_TALLY_SRC__ === "string") {
      return window.__AMOS_DEFAULT_TALLY_SRC__;
    }
    return "https://tally.so/r/mezJpo?transparentBackground=1&formEventsForwarding=1";
  }, []);

  React.useEffect(() => {
    if (!open) return undefined;
    prevOverflowRef.current = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = prevOverflowRef.current;
    };
  }, [open]);

  React.useEffect(() => {
    if (!open) return undefined;
    const run = () => {
      if (typeof window.Tally !== "undefined" && typeof window.Tally.loadEmbeds === "function") {
        window.Tally.loadEmbeds();
        return true;
      }
      return false;
    };
    run();
    let done = false;
    const id = window.setInterval(() => {
      if (done) return;
      if (run()) {
        done = true;
        window.clearInterval(id);
      }
    }, 50);
    const t = window.setTimeout(() => {
      done = true;
      window.clearInterval(id);
    }, 8000);
    return () => {
      done = true;
      window.clearInterval(id);
      window.clearTimeout(t);
    };
  }, [open]);

  if (!open) return null;

  return (
    <div
      className="tally-fullscreen-overlay"
      role="dialog"
      aria-modal="true"
      aria-label="Request Access application"
    >
      <button
        type="button"
        className="tally-fullscreen-close"
        onClick={onClose}
        aria-label="Close"
      >
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" aria-hidden="true">
          <path
            d="M18 6L6 18M6 6l12 12"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
          />
        </svg>
      </button>
      <iframe
        key={tallySrc}
        data-tally-src={tallySrc}
        width="100%"
        height="100%"
        frameBorder={0}
        title="Request Access application"
        className="tally-fullscreen-iframe"
      />
    </div>
  );
}
