export type LinkFieldValue = {
  url?: {
    href?: string;
    type?: string;
  };
  open_in_new_tab?: boolean;
  no_follow?: boolean;
};

export function getLinkRel(target: string, rel: string) {
  const relValues = [];

  if (target === '_blank') {
    relValues.push('noopener', 'noreferrer');
  }
  if (rel === 'nofollow') {
    relValues.push('nofollow');
  }
  return relValues.length > 0 ? relValues.join(' ') : undefined;
}

export function getLinkFieldRel(fieldValue?: LinkFieldValue) {
  if (!fieldValue) return undefined;

  const target = fieldValue.open_in_new_tab ? '_blank' : '_self';
  const rel = fieldValue.no_follow ? 'nofollow' : '';

  return getLinkRel(target, rel);
}

export function getLinkFieldTarget(
  fieldValue?: LinkFieldValue
): '_self' | '_blank' | '_parent' | '_top' {
  if (!fieldValue) return '_self';

  return fieldValue.open_in_new_tab ? '_blank' : '_self';
}

/**
 * Extracts the host from a given URL by removing the protocol (http:// or https://)
 * and optional prefixes (www. or open.). It then splits the URL by the first slash to get only the host.
 *
 * @param {string} href - The URL from which to extract the host.
 * @returns {string} - The extracted host part of the URL.
 *
 * Example:
 * const href = "https://podcasts.apple.com";
 * const host = getHostFromUrl(socialLink);
 * console.log(host); // Output: "podcasts.apple.com"
 */

function getHostFromUrl(href: string) {
  return href.replace(/https?:\/\/(www\.|open\.)?/, '').split('/')[0];
}

export function getHost(linkType: string, href: string) {
  if (linkType === 'EMAIL_ADDRESS') {
    return 'email';
  }

  return getHostFromUrl(href);
}
