'use client';

/**
 * Auth0 OAuth callback page.
 *
 * Auth0 redirects here after the user authenticates with Google.
 * We pick up the access token via useAuth0(), exchange it for a backend
 * session token, then redirect to the home page.
 */

import { useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth0 } from '@auth0/auth0-react';
import { loginWithAuth0Token, isAuthenticated, getSafeRedirectUrl } from '@/lib/auth';
import { useTranslation } from '@/lib/i18n';

export default function Auth0CallbackPage() {
  const router = useRouter();
  const { t } = useTranslation();
  const { isLoading, isAuthenticated: auth0LoggedIn, getAccessTokenSilently, error } = useAuth0();
  const exchanged = useRef(false);

  useEffect(() => {
    if (isLoading || exchanged.current) return;

    if (error) {
      router.replace(`/login?error=${encodeURIComponent(error.message)}`);
      return;
    }

    if (!auth0LoggedIn) return;

    exchanged.current = true;
    (async () => {
      try {
        const accessToken = await getAccessTokenSilently();
        await loginWithAuth0Token(accessToken);
        const stored = sessionStorage.getItem('investibook_login_redirect');
        sessionStorage.removeItem('investibook_login_redirect');
        router.replace(getSafeRedirectUrl(stored));
      } catch (err: unknown) {
        const msg = err instanceof Error ? err.message : t('authCallback.failedDefault');
        router.replace(`/login?error=${encodeURIComponent(msg)}`);
      }
    })();
  }, [isLoading, auth0LoggedIn, error, getAccessTokenSilently, router, t]);

  // Already have a backend token (e.g. page refresh) — go home directly.
  useEffect(() => {
    if (isAuthenticated()) {
      const stored = sessionStorage.getItem('investibook_login_redirect');
      sessionStorage.removeItem('investibook_login_redirect');
      router.replace(getSafeRedirectUrl(stored));
    }
  }, [router]);

  return (
    <div
      style={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        background: 'linear-gradient(135deg, #f5f7ff 0%, #eef0fb 100%)',
        flexDirection: 'column',
        gap: 16,
      }}
    >
      <div
        style={{
          width: 40,
          height: 40,
          border: '3px solid #e0e0ef',
          borderTopColor: '#5c5fbc',
          borderRadius: '50%',
          animation: 'spin 0.8s linear infinite',
        }}
      />
      <p style={{ color: '#6b7280', fontSize: 15, margin: 0 }}>{t('authCallback.signingInLong')}</p>
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );
}
