import { useCallback } from 'react';
import { useCrossProductUrlWrapper } from '@atlaskit/analytics-cross-product/useCrossProductUrlWrapper';
import { useSmartLinkContext } from '@atlaskit/link-provider';
import { functionWithFG } from '@atlaskit/platform-feature-flags-react';
const SMART_LINKS_XPC_BRIDGE = 'smartLinks';
const XPC_QUERY_PARAM = 'xpis';
export const getIsFirstPartyLink = details => {
  var _is1PLink, _details$meta;
  return ((_is1PLink = details === null || details === void 0 ? void 0 : (_details$meta = details.meta) === null || _details$meta === void 0 ? void 0 : _details$meta.is1PLink) !== null && _is1PLink !== void 0 ? _is1PLink : false) === true;
};
const identityUrlWrapper = url => url;
const useSmartLinkCrossProductUrlWrapperFallback = _args => identityUrlWrapper;
const useSmartLinkCrossProductUrlWrapper = ({
  details
}) => {
  var _product$toLowerCase;
  const {
    product,
    bridgeProduct
  } = useSmartLinkContext();
  const wrapUrl = useCrossProductUrlWrapper({
    bridge: bridgeProduct !== null && bridgeProduct !== void 0 ? bridgeProduct : SMART_LINKS_XPC_BRIDGE,
    product: (_product$toLowerCase = product === null || product === void 0 ? void 0 : product.toLowerCase()) !== null && _product$toLowerCase !== void 0 ? _product$toLowerCase : 'unknown'
  });
  return useCallback(url => {
    if (!getIsFirstPartyLink(details) || !product) {
      return url;
    }
    let parsedUrl;
    try {
      parsedUrl = new URL(url);
    } catch {
      return url;
    }
    if (parsedUrl.searchParams.has(XPC_QUERY_PARAM)) {
      return url;
    }
    return wrapUrl(url);
  }, [details, product, wrapUrl]);
};
export const useSmartLinkCrossProductUrlWrapperGated = functionWithFG('platform_smartlink_xpc_url_wrapping', useSmartLinkCrossProductUrlWrapper, useSmartLinkCrossProductUrlWrapperFallback);