// Email-capture popup modal — locked portal aesthetic.
// Dark overlay, cream card with hairline border + 18px radius. Cormorant
// display headline, Jost 300 body. On submit the card content swaps to a
// confirmation state that reveals the surprise (a juice from The Press).
// The reward is NEVER mentioned before submit — no discount language anywhere.
function EmailModal() {
  const [open, setOpen] = React.useState(false);
  const [sent, setSent] = React.useState(false);
  const cardRef = React.useRef(null);

  // Sequencing: never overlap the cookie banner. We wait until the visitor has
  // resolved cookie consent, THEN arm two triggers — a 20s dwell timer and
  // exit-intent — whichever fires first. Shown at most once per session.
  React.useEffect(() => {
    if (sessionStorage.getItem("nourrir_table_seen")) return;

    let dwellTimer = null;
    let pollTimer = null;
    let armed = false;

    const reveal = () => {
      if (armed) return;
      armed = true;
      cleanup();
      setOpen(true);
    };

    const onExit = (e) => {
      // exit-intent: pointer leaves through the top of the viewport
      if (e.clientY <= 0) reveal();
    };

    const arm = () => {
      dwellTimer = setTimeout(reveal, 20000);          // 20s dwell
      document.addEventListener("mouseout", onExit);   // or exit-intent
    };

    const cleanup = () => {
      clearTimeout(dwellTimer);
      clearInterval(pollTimer);
      document.removeEventListener("mouseout", onExit);
    };

    const cookieResolved = () => {
      try { return !!localStorage.getItem("nourrir.cookieConsent"); }
      catch (e) { return true; }
    };

    if (cookieResolved()) {
      arm();
    } else {
      // poll until the banner is dismissed/resolved, then start the triggers
      pollTimer = setInterval(() => {
        if (cookieResolved()) { clearInterval(pollTimer); arm(); }
      }, 400);
    }

    return cleanup;
  }, []);

  // Esc to close; lock body scroll while open.
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") close(); };
    window.addEventListener("keydown", onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = prev; };
  }, [open]);

  function close() {
    setOpen(false);
    sessionStorage.setItem("nourrir_table_seen", "1");
  }

  function submit(e) {
    e.preventDefault();
    setSent(true);
  }

  if (!open) return null;

  return (
    <div className="tm-overlay" onMouseDown={(e) => { if (e.target === e.currentTarget) close(); }}>
      <div className="tm-card" ref={cardRef} role="dialog" aria-modal="true"
           aria-label="Join the table">
        <button className="tm-close" type="button" aria-label="Close" onClick={close}>
          <svg width="12" height="12" viewBox="0 0 12 12" aria-hidden="true">
            <path d="M1 1l10 10M11 1L1 11" stroke="currentColor" strokeWidth="0.9" strokeLinecap="round"/>
          </svg>
        </button>

        {sent ? (
          <div className="tm-body tm-body--done">
            <h2 className="tm-title">You're in.</h2>
            <p className="tm-sub">
              While the doors are open, your place is held.
            </p>
          </div>
        ) : (
          <div className="tm-body">
            <h2 className="tm-title">Join The Table.</h2>
            <p className="tm-sub">Soon, The Table will be invitation only. For now, the doors are open.</p>

            <form className="tm-form" onSubmit={submit}>
              <input className="tm-field" type="email" name="email"
                     placeholder="Email" autoComplete="email" required/>

              <button className="tm-submit" type="submit">Join</button>
            </form>

            <p className="tm-fine">
              By joining you agree to receive occasional emails from nourrir. about menus,
              openings and seasonal news. Unsubscribe anytime.
            </p>
          </div>
        )}
      </div>
    </div>
  );
}
window.EmailModal = EmailModal;
