import { withQuery, getQuery } from 'ufo';

function isExternal(url: string): boolean {
  try {
    const u = new URL(url);
    return u.origin !== window.location.origin;
  } catch {
    return false;
  }
}

/**
 *
 * 为外部 URL 添加 UTM 追踪参数
 * @param url - 原始 URL 地址
 * @param section - 导航区域，可选值为 'header' 或 'footer'
 * @returns 添加 UTM 参数后的 URL
 * @see https://team.arcblock.io/comment/discussions/7504c5ce-7453-4223-a539-27620efcf38e/#189d3749-e4bb-4588-9b7c-9b006fc3ef35
 *
 */
export function getUTMUrl(url: string, section: 'header' | 'footer'): string {
  try {
    if (!isExternal(url)) {
      return url;
    }

    const existsQueryParams = getQuery(url);

    const queryParams = {
      // 自身站点的 hostname
      utm_source: window.location.hostname,
      // 标记导航点击
      utm_medium: `${section}_nav`,
      // 全局导航统一标签
      utm_campaign: `global_${section}_menu`,
      // 目标站点标识
      utm_content: new URL(url).hostname,
      ...existsQueryParams,
    };

    return withQuery(url, queryParams);
  } catch (error) {
    console.error('Failed to generate UTM URL:', error);
    return url;
  }
}
