// Auth gate + sign-in screen + user menu.

function AuthScreen({ error }) {
  const go = () => { window.location.href = window.SnatchAPI.googleLoginUrl(window.location.href); };

  return (
    <div style={{
      minHeight: '100vh', background: '#0a0a0a', color: '#fff',
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      padding: 24, textAlign: 'center',
    }}>
      <div style={{ maxWidth: 440, width: '100%' }}>
        <div className="mono" style={{ fontSize: 11, letterSpacing: '0.3em', color: 'var(--accent)' }}>● SNATCH</div>
        <div className="display" style={{ fontSize: 'clamp(56px, 9vw, 96px)', marginTop: 14 }}>Sign in<br/>to train.</div>
        <p style={{ color: 'rgba(255,255,255,0.55)', fontSize: 15, lineHeight: 1.5, marginTop: 18 }}>
          Your saved WODs and chat history follow you across devices. No spam. No password to forget.
        </p>

        <button onClick={go} style={{
          marginTop: 28, width: '100%', padding: '16px 20px',
          background: '#fff', color: '#0a0a0a', border: 0, borderRadius: 4,
          fontFamily: 'Archivo', fontWeight: 700, fontSize: 15, letterSpacing: '0.04em',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 12, cursor: 'pointer',
        }}>
          <GoogleGlyph /> Continue with Google
        </button>

        {error === 'google_not_configured' && (
          <div style={{ marginTop: 18, padding: 14, border: '1px solid rgba(255,45,45,0.35)', background: 'rgba(255,45,45,0.08)', color: '#fca', fontSize: 13, lineHeight: 1.45, borderRadius: 4 }}>
            Google sign-in isn't configured yet. The site owner needs to add <span className="mono">GOOGLE_CLIENT_ID</span> + <span className="mono">GOOGLE_CLIENT_SECRET</span> worker secrets.
          </div>
        )}
        {error && error !== 'google_not_configured' && (
          <div style={{ marginTop: 18, padding: 14, border: '1px solid rgba(255,45,45,0.35)', background: 'rgba(255,45,45,0.08)', color: '#fca', fontSize: 13, borderRadius: 4 }}>
            Sign-in failed: {error}
          </div>
        )}

        <div className="mono" style={{ marginTop: 36, fontSize: 10, letterSpacing: '0.22em', opacity: 0.4 }}>
          MORE SIGN-IN OPTIONS COMING SOON
        </div>
      </div>
    </div>
  );
}

function GoogleGlyph() {
  return (
    <svg width="18" height="18" viewBox="0 0 48 48" aria-hidden="true">
      <path fill="#FFC107" d="M43.6 20.5H42V20H24v8h11.3A12 12 0 1 1 24 12a11.9 11.9 0 0 1 8.4 3.3l5.7-5.7A20 20 0 1 0 44 24a20 20 0 0 0-.4-3.5z"/>
      <path fill="#FF3D00" d="M6.3 14.7l6.6 4.8A12 12 0 0 1 24 12a11.9 11.9 0 0 1 8.4 3.3l5.7-5.7A20 20 0 0 0 6.3 14.7z"/>
      <path fill="#4CAF50" d="M24 44a20 20 0 0 0 13.5-5.2l-6.2-5.3A12 12 0 0 1 12.7 28l-6.5 5A20 20 0 0 0 24 44z"/>
      <path fill="#1976D2" d="M43.6 20.5H42V20H24v8h11.3a12 12 0 0 1-4 5.5l6.2 5.3C41.1 36.2 44 30.6 44 24a20 20 0 0 0-.4-3.5z"/>
    </svg>
  );
}

function UserMenu({ user, onLogout }) {
  const [open, setOpen] = React.useState(false);
  const initial = (user.display_name || user.email || '?').slice(0, 1).toUpperCase();

  return (
    <div style={{ position: 'relative' }}>
      <button
        onClick={() => setOpen(v => !v)}
        style={{
          width: 34, height: 34, borderRadius: '50%',
          background: user.avatar_url ? `url(${user.avatar_url}) center/cover` : 'linear-gradient(135deg, var(--accent), #ff8a3d)',
          border: '2px solid #fff', cursor: 'pointer', padding: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: '#fff', fontFamily: 'Archivo', fontWeight: 800, fontSize: 13,
        }}
        aria-label="Account menu"
      >
        {!user.avatar_url ? initial : null}
      </button>
      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 500 }} />
          <div style={{
            position: 'absolute', right: 0, top: '110%', zIndex: 501,
            width: 240, background: '#151515', border: '1px solid #2a2a2a',
            borderRadius: 6, padding: 14, boxShadow: '0 20px 40px rgba(0,0,0,0.5)',
            color: '#fff',
          }}>
            <div style={{ fontSize: 14, fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{user.display_name || 'Athlete'}</div>
            <div className="mono" style={{ fontSize: 11, opacity: 0.55, marginTop: 4, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{user.email}</div>
            <button
              onClick={onLogout}
              style={{
                marginTop: 14, width: '100%', padding: '10px 12px',
                background: 'transparent', border: '1px solid rgba(255,255,255,0.2)',
                color: '#fff', fontFamily: 'Archivo', fontWeight: 700, fontSize: 12,
                letterSpacing: '0.08em', textTransform: 'uppercase', cursor: 'pointer', borderRadius: 3,
              }}
            >
              Log out
            </button>
          </div>
        </>
      )}
    </div>
  );
}

function useAuthGate() {
  const [state, setState] = React.useState({ loading: true, user: null, error: null });

  React.useEffect(() => {
    // Read ?auth_error= from URL once and strip it.
    const url = new URL(window.location.href);
    const authError = url.searchParams.get('auth_error');
    if (authError) {
      url.searchParams.delete('auth_error');
      window.history.replaceState({}, '', url.toString());
    }
    const signedIn = url.searchParams.get('signed_in');
    if (signedIn) {
      url.searchParams.delete('signed_in');
      window.history.replaceState({}, '', url.toString());
    }

    window.SnatchAPI.me()
      .then(d => setState({ loading: false, user: d.user, error: authError }))
      .catch(err => {
        if (err.status === 401) setState({ loading: false, user: null, error: authError });
        else setState({ loading: false, user: null, error: err.message });
      });
  }, []);

  const logout = React.useCallback(async () => {
    try { await window.SnatchAPI.logout(); } catch {}
    setState({ loading: false, user: null, error: null });
  }, []);

  return { ...state, logout };
}

Object.assign(window, { AuthScreen, UserMenu, useAuthGate });
