// ─── Login Modal ─────────────────────────────────────────────
// Renders over the main homepage. Opens when:
//   • window.OPEN_LOGIN === true  (set by server when visiting /login.html directly)
//   • 'not:modal' event with detail 'login'  (triggered by Header "Sign in" link)
// Closing navigates to '/' if on /login.html, else stays on current page.

function LoginModal() {
  const [open, setOpen] = React.useState(!!(window.OPEN_LOGIN));

  React.useEffect(() => {
    function onModal(e) { if (e.detail === 'login') setOpen(true); }
    function onPop()   { if (!window.location.pathname.includes('login')) setOpen(false); }
    window.addEventListener('not:modal', onModal);
    window.addEventListener('popstate',  onPop);
    return () => {
      window.removeEventListener('not:modal', onModal);
      window.removeEventListener('popstate',  onPop);
    };
  }, []);

  React.useEffect(() => {
    function onKey(e) { if (e.key === 'Escape') handleClose(); }
    if (open) document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open]);

  function handleClose() {
    setOpen(false);
    if (window.location.pathname.includes('login')) {
      if (window.history.state && window.history.state.notModal) {
        history.back();
      } else {
        history.pushState({}, '', '/');
      }
    } else {
      history.pushState({}, '', window.location.pathname + window.location.search);
    }
  }

  if (!open) return null;

  return (
    <div className="abt-overlay" onClick={handleClose}>
      <div className="abt-panel lgn-panel" onClick={e => e.stopPropagation()}>

        <div className="abt-head">
          <span className="abt-label">Sign In</span>
          <button className="abt-close" onClick={handleClose}>✕ close</button>
        </div>

        <div className="lgn-body">
          <p className="lgn-lead">Sign in to contribute photos and connections to the archive.</p>
          <a href="/api/auth/google" className="lgn-google-btn">
            <img src="https://www.google.com/favicon.ico" width="18" height="18" alt="" />
            Continue with Google
          </a>
          <p className="lgn-terms mono">
            By continuing, you agree to our{' '}
            <a href="/terms" onClick={e => { e.preventDefault(); handleClose(); openModal('terms', '/terms'); }}>Terms</a>
            {' '}and{' '}
            <a href="/privacy" onClick={e => { e.preventDefault(); handleClose(); openModal('privacy', '/privacy'); }}>Privacy Policy</a>.
          </p>
        </div>

      </div>
    </div>
  );
}

Object.assign(window, { LoginModal });
