// Auth gate modal: blocking overlay shown when an unauthenticated user reaches a protected route

const AuthGateModal = ({ route }) => {
  const t = useT();
  const a = t.auth.gate;

  // Encode route as the `next` param so login/register can return here
  const nextParam = encodeURIComponent('#' + (route || '/'));

  // ESC closes (back to home)
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') navigateTo('/'); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, []);

  const onOverlayClick = (e) => { if (e.target === e.currentTarget) navigateTo('/'); };

  return (
    <div
      className="pb-auth-gate-overlay"
      onClick={onOverlayClick}
      role="dialog"
      aria-modal="true"
      aria-labelledby="pb-auth-gate-title"
      data-testid="auth-gate-modal"
    >
      <div className="pb-auth-gate-card">
        <button
          className="pb-auth-gate-close"
          aria-label={a.dismiss}
          onClick={() => navigateTo('/')}
        >✕</button>
        <PBLogo size={36} />
        <h2 id="pb-auth-gate-title" className="pb-auth-gate-title">{a.title}</h2>
        <p className="pb-auth-gate-sub">{a.subtitle}</p>
        <div className="pb-auth-gate-actions">
          <button
            className="pb-btn pb-btn-primary"
            onClick={() => navigateTo('/login?next=' + nextParam)}
            data-testid="auth-gate-signin"
          >{a.sign_in}</button>
          <button
            className="pb-btn pb-btn-ghost"
            onClick={() => navigateTo('/register?next=' + nextParam)}
            data-testid="auth-gate-signup"
          >{a.sign_up}</button>
        </div>
      </div>
    </div>
  );
};

window.AuthGateModal = AuthGateModal;
