import {JSX, useEffect} from 'react';
import {useNavigate, useLocation} from 'react-router-dom';

interface QueryPreservingRedirectProps {
  to: string;
  replace?: boolean;
}

export function QueryPreservingRedirect({to, replace = true}: QueryPreservingRedirectProps): JSX.Element | null {
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    // Preserve query parameters and hash
    const currentSearch = location.search;
    const currentHash = location.hash;

    // Build the redirect URL with preserved query parameters and hash
    let redirectUrl = to;
    if (currentSearch) {
      redirectUrl += currentSearch;
    }
    if (currentHash) {
      redirectUrl += currentHash;
    }

    console.log('QueryPreservingRedirect: Root route redirect detected');
    console.log('Original path:', location.pathname);
    console.log('Query parameters:', currentSearch || '(none)');
    console.log('Hash:', currentHash || '(none)');
    console.log('Redirecting to:', redirectUrl);
    console.log('Full original URL:', window.location.href);

    // Small delay to ensure console logs are visible
    setTimeout(() => {
      navigate(redirectUrl, {replace});
    }, 100);
  }, [navigate, location, to, replace]);

  // Return null since this is just a redirect component
  return null;
}
