import { useEffect, useRef } from 'react';
import { useLogto } from '@logto/react';
import { useNavigate } from 'react-router';
import { Spinner } from '@cameleer/design-system';

export function RegisterPage() {
  const { signIn, isAuthenticated, isLoading } = useLogto();
  const navigate = useNavigate();
  const redirected = useRef(false);

  useEffect(() => {
    if (isAuthenticated) {
      navigate('/', { replace: true });
    }
  }, [isAuthenticated, navigate]);

  useEffect(() => {
    if (!isLoading && !isAuthenticated && !redirected.current) {
      redirected.current = true;
      signIn({
        redirectUri: `${window.location.origin}/platform/callback`,
        firstScreen: 'register',
      });
    }
  }, [isLoading, isAuthenticated, signIn]);

  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh' }}>
      <Spinner />
    </div>
  );
}
