// eslint-disable-next-line import/no-extraneous-dependencies
import { NavigateFunction } from 'react-router-dom';
import { joinURL } from 'ufo';
import { getPrefix, PAYMENT_KIT_DID } from './util';

export interface LinkInfo {
  // Full URL for href attribute
  url: string;
  // Whether this is an external link
  external: boolean;
  // Original path (used for React Router)
  path: string;
}

/**
 * Check if currently running inside Payment Kit
 */
export function isInPaymentKit(): boolean {
  const componentId = (window.blocklet?.componentId || '').split('/').pop();
  return componentId === PAYMENT_KIT_DID;
}

/**
 * Create link information object
 * @param path Path or URL
 * @param external Force external link behavior
 */
export function createLink(path: string, external = false): LinkInfo {
  const isAbsoluteUrl = /^https?:\/\//.test(path);
  const isExternal = external || isAbsoluteUrl;
  const url = isExternal ? path : joinURL(getPrefix(), path);
  return {
    url,
    external: isExternal,
    path,
  };
}

/**
 * Get HTML attributes for a link
 * @param link Link information
 * @param target Link target (default: _self)
 */
export function getLinkProps(link: LinkInfo, target = '_self'): Record<string, any> {
  const props: Record<string, any> = {
    href: link.url,
  };

  if (link.external) {
    props.target = target;
    props.rel = target === '_blank' ? 'noopener noreferrer' : undefined;
  }

  return props;
}

/**
 * Handle link navigation
 * @param e Click event
 * @param link Link information
 * @param navigate React Router navigate function
 * @param options Navigation options
 */
export function handleNavigation(
  e: React.MouseEvent,
  link: LinkInfo,
  navigate?: NavigateFunction,
  options: { replace?: boolean; target?: string } = {}
): void {
  if (e) {
    e.preventDefault();
  }
  const { replace = false, target = '_self' } = options;
  if (link.external || target === '_blank') {
    window.open(link.url, target);
    return;
  }

  if (isInPaymentKit() && navigate) {
    navigate(link.path, { replace });
    return;
  }

  if (replace) {
    window.location.replace(link.url);
  } else {
    window.location.href = link.url;
  }
}
