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;
export const useSmartLinkCrossProductUrlWrapper = ({
  details
}) => {
  var _effectiveProduct$toL;
  const {
    product,
    bridgeProduct,
    xpcProduct,
    xpcSubProduct
  } = useSmartLinkContext();
  // xpcProduct takes precedence over product — it identifies the host product for XPC analytics
  // without affecting link resolution (which uses the `product` prop separately).
  const effectiveProduct = xpcProduct !== null && xpcProduct !== void 0 ? xpcProduct : product;
  const effectiveBridge = bridgeProduct !== null && bridgeProduct !== void 0 ? bridgeProduct : SMART_LINKS_XPC_BRIDGE;
  const effectiveProductForWrapper = (_effectiveProduct$toL = effectiveProduct === null || effectiveProduct === void 0 ? void 0 : effectiveProduct.toLowerCase()) !== null && _effectiveProduct$toL !== void 0 ? _effectiveProduct$toL : 'unknown';
  const wrapUrl = useCrossProductUrlWrapper({
    bridge: effectiveBridge,
    product: effectiveProductForWrapper,
    ...(xpcSubProduct ? {
      subProduct: xpcSubProduct
    } : {})
  });
  return useCallback(url => {
    if (typeof window === 'undefined' || !getIsFirstPartyLink(details) || !effectiveProduct) {
      return url;
    }
    let parsedUrl;
    try {
      parsedUrl = new URL(url);
    } catch {
      return url;
    }
    if (parsedUrl.searchParams.has(XPC_QUERY_PARAM)) {
      return url;
    }
    return wrapUrl(url);
  },
  // Keep bridge/subproduct in the dependency array so consumers that memoize this callback
  // refresh when mini-modal context updates from smartLinks to rovo-chat.
  // eslint-disable-next-line react-hooks/exhaustive-deps
  [details, effectiveBridge, effectiveProduct, wrapUrl, xpcSubProduct]);
};
export const useSmartLinkCrossProductUrlWrapperGated = functionWithFG('platform_smartlink_xpc_url_wrapping', useSmartLinkCrossProductUrlWrapper, useSmartLinkCrossProductUrlWrapperFallback);