const { useEffect, useState } = React;

/**
 * AuthCallback — Handles the stateless OAuth 2.0 redirection landing.
 * Parses the signed JWT, user name, and email from the query string, stores them in
 * localStorage matching the existing session schema, and navigates to the home room.
 */
function AuthCallback({ onNavigate }) {
  const [error, setError] = useState(null);

  useEffect(() => {
    // 1. Instantly capture redirect query parameters
    const params = new URLSearchParams(window.location.search);
    const token = params.get('token');
    const name = params.get('name') || 'User';
    const email = params.get('email') || '';
    const errCode = params.get('error');

    // 2. Immediately replace window history to purge token/secrets from browser address bar
    const cleanUrl = window.location.pathname;
    window.history.replaceState({}, document.title, cleanUrl);

    if (token) {
      try {
        // 3. Persist session in localStorage with the exact same structure as email/password auth
        localStorage.setItem("herely.session", JSON.stringify({
          user: { name, email },
          token
        }));
        
        // 4. Smooth soft transition to the authenticated home page
        if (onNavigate) {
          onNavigate("/home");
        } else {
          window.location.href = "/home";
        }
      } catch (e) {
        console.error("Failed to store Google OAuth session in localStorage:", e);
        setError("server_error");
      }
    } else if (errCode) {
      setError(errCode);
    } else {
      setError("invalid_request");
    }
  }, [onNavigate]);

  // Map OAuth/Server error codes to friendly premium validation messages
  const getErrorMessage = () => {
    switch (error) {
      case 'cancelled':
        return 'Authentication was cancelled. You can try signing in again.';
      case 'no_email':
        return 'LinkedIn did not return an email address. Herely requires an email address to create a secure account.';
      case 'server_error':
        return 'An error occurred on the server during sign-in. Please try again.';
      case 'invalid_request':
        return 'Invalid authentication request. Please go back and try again.';
      default:
        return 'Failed to authenticate. Please try again.';
    }
  };

  if (error) {
    return (
      <div className="auth-viewport midnight" style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center" }}>
        <div className="auth-wrapper" style={{ display: "flex", justifyContent: "center" }}>
          <div className="auth-card rv in" style={{ textAlign: "center", maxWidth: "440px", animation: "pill-in 900ms cubic-bezier(.2,.7,.2,1) both" }}>
            <header className="auth-header">
              <div className="eyebrow" style={{ color: "var(--m-coral)" }}>Authentication Failed</div>
              <h1 className="auth-title" style={{ fontSize: "28px" }}>Sign-in <span className="ed">unsuccessful</span></h1>
              <p className="auth-subtitle" style={{ marginTop: "16px", color: "var(--mute)", fontSize: "14px", lineHeight: "1.6" }}>
                {getErrorMessage()}
              </p>
            </header>
            
            <button 
              type="button" 
              className="btn btn-primary btn-full"
              style={{ marginTop: "28px" }}
              onClick={() => {
                if (onNavigate) onNavigate("/sign-in");
                else window.location.href = "/sign-in";
              }}
            >
              Back to Sign In
            </button>
          </div>
        </div>
      </div>
    );
  }

  // Pure premium invisible loading state utilizing pre-existing app ring configurations
  return (
    <div className="auth-viewport midnight" style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center" }}>
      <div className="scanqr-loading rv in" style={{ animation: "pill-in 900ms cubic-bezier(.2,.7,.2,1) both" }}>
        <div className="loading-visual">
          <div className="loading-rings">
            <div className="l-ring r1"></div>
            <div className="l-ring r2"></div>
            <div className="l-ring r3"></div>
          </div>
          <div className="loading-dots">
            <span className="l-dot blue"></span>
            <span className="l-dot amber"></span>
            <span className="l-dot teal"></span>
          </div>
        </div>
        <div className="loading-text" style={{ marginTop: "24px" }}>
          <div className="mono" style={{ color: "var(--mute)", letterSpacing: "0.14em" }}>Authenticating...</div>
        </div>
      </div>
    </div>
  );
}

// Bind to global window scope so Babel transpilation links it to other components
Object.assign(window, { AuthCallback });
