import { useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { handleCallback, userManager } from './oidc';
import { consumeReturnUrl } from './sessionRedirect';
import { Spin } from 'antd';

export default function AuthCallback() {
  const navigate = useNavigate();
  const processed = useRef(false);

  useEffect(() => {
    if (processed.current) return;
    processed.current = true;

    // Behandelt Silent Renew im Iframe
    if (window !== window.parent || window.opener) {
      userManager.signinSilentCallback().catch(err => {
        console.error('Silent renew callback error:', err);
      });
      return;
    }

    handleCallback()
      .then(() => navigate(consumeReturnUrl(), { replace: true }))
      .catch((err) => {
        console.error('Auth Callback Fehler:', err);
        navigate('/login', { replace: true });
      });
  }, [navigate]);

  return (
    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
      <Spin size="large" description="Anmeldung wird verarbeitet..." />
    </div>
  );
}
