import { useCallback } from 'react';
import { useRouter } from 'next/router';
import { resolveElectionLink } from "../../../utils/election/index.js";
import usePageType from '../usePageType';
import usePagesManifest from '../usePagesManifest';
import usePagePathPrefix from '../usePagePathPrefix';

/**
 * Get an imperative callback that lets you link to an election page or other
 * URL after some user-triggered event. Note that you should generally use
 * `ElectionLink`; this is only for cases when you _have_ to navigate
 * imperatively.
 */
const useNavigate = function useNavigate() {
  const router = useRouter();
  const pageType = usePageType();
  const pagePathPrefix = usePagePathPrefix();
  const manifest = usePagesManifest();
  return useCallback(link => {
    const {
      url,
      targetType
    } = resolveElectionLink({
      manifest,
      pagePathPrefix,
      link,
      currentUrl: router?.asPath
    });
    if (!url) return;

    // open external links in new tab always
    if (targetType === 'external') {
      window.open(url, '_blank').focus();
      return;
    }

    // use next for on-page routing
    if (pageType === 'page') {
      router.push(url);
      return;
    }

    // fall back to regular page navigation
    window.location.href = url;
  }, [pagePathPrefix, manifest, pageType, router]);
};
export default useNavigate;