import React, { useEffect, useState } from 'react';
import { Navigate, useNavigate } from 'react-router-dom';
import { resolveAuthenticatedRoute } from '../utils/appRouting';

const AppEntry: React.FC = () => {
  const navigate = useNavigate();
  const [target, setTarget] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;

    resolveAuthenticatedRoute()
      .then((route) => {
        if (cancelled) return;
        if (route) {
          setTarget(route);
        } else {
          navigate('/login', { replace: true });
        }
      })
      .catch(() => {
        if (!cancelled) {
          navigate('/login', { replace: true });
        }
      });

    return () => {
      cancelled = true;
    };
  }, [navigate]);

  if (target) {
    return <Navigate to={target} replace />;
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
      <div className="text-center">
        <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-indigo-600 mx-auto" />
        <p className="mt-4 text-gray-600 dark:text-gray-400 text-sm">Loading...</p>
      </div>
    </div>
  );
};

export default AppEntry;
