import React from 'react';
import { browser } from '@atlaskit/linking-common/user-agent';
import { functionWithCondition } from '@atlaskit/platform-feature-flags-react';
import { expValEquals } from '@atlaskit/tmp-editor-statsig/exp-val-equals';
import { useLinkClicked, useMouseDownEvent } from '../../state/analytics/useLinkClicked';
import { ANALYTICS_CHANNEL } from './analytics';
export const buttonMap = new Map([[undefined, 'none'], [0, 'left'], [1, 'middle'], [2, 'right']]);
export const getKeys = e => {
  return ['alt', 'ctrl', 'meta', 'shift'].filter(key => e[`${key}Key`] === true);
};
const isContentEditable = el => {
  return el instanceof HTMLElement && el.isContentEditable;
};
export function getLinkClickOutcome(e, clickType) {
  const {
    mac,
    safari
  } = browser();

  /**
   * If the link/parent is content editable then left click won't have typical effect
   */
  if (isContentEditable(e.currentTarget) && ['left', 'middle'].includes(clickType)) {
    return 'contentEditable';
  }
  switch (clickType) {
    case 'left':
    case 'keyboard':
      {
        // Meta key = Cmd for macOS, Windows key sometimes for Windows (otherwise false)
        // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/metaKey
        if (e.metaKey) {
          return mac ? 'clickThroughNewTabOrWindow' : 'clickThrough';
        }
        if (e.shiftKey) {
          // Alt/option click in safari typically adds the link to bookmarks
          if (safari) {
            return 'alt';
          }
          return 'clickThroughNewTabOrWindow';
        }
        if (e.ctrlKey) {
          // Ctrl+Left on macOS defaults to triggering a right click instead (so won't trigger onClick)
          // but if this behaviour is disabled, likely outcome is clickThrough
          if (mac) {
            return 'clickThrough';
          }
          return 'clickThroughNewTabOrWindow';
        }
        if (e.altKey) {
          return 'alt';
        }
        const target = e.currentTarget.getAttribute('target');
        if (target === '_blank') {
          return 'clickThroughNewTabOrWindow';
        }
        return 'clickThrough';
      }
    case 'middle':
      {
        return 'clickThroughNewTabOrWindow';
      }
    case 'right':
      {
        return 'contextMenu';
      }
  }
  return 'unknown';
}
const linkClickedEventOld = ({
  clickType,
  clickOutcome,
  keysHeld,
  defaultPrevented
}) => ({
  action: 'clicked',
  actionSubject: 'link',
  eventType: 'ui',
  attributes: {
    clickType,
    clickOutcome,
    keysHeld,
    defaultPrevented
  }
});
const linkClickedEventWithShortLink = ({
  clickType,
  clickOutcome,
  keysHeld,
  defaultPrevented,
  isConfluenceShortLink
}) => ({
  action: 'clicked',
  actionSubject: 'link',
  eventType: 'ui',
  attributes: {
    clickType,
    clickOutcome,
    keysHeld,
    defaultPrevented,
    isConfluenceShortLink
  }
});
export const createLinkClickedPayloadOld = event => {
  // Through the `detail` property, we're able to determine if the event is (most likely) triggered via keyboard
  // https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail
  const isKeyboard = event.nativeEvent.detail === 0;
  const clickType = isKeyboard ? 'keyboard' : buttonMap.get(event.button);
  if (!clickType) {
    return;
  }
  const clickOutcome = getLinkClickOutcome(event, clickType);
  const keysHeld = getKeys(event);
  const defaultPrevented = event.defaultPrevented;
  const linkClickedEventResult = linkClickedEventOld({
    clickType,
    clickOutcome,
    keysHeld,
    defaultPrevented
  });

  // if the current target is an anchor tag, we can get the href from it and use that as the url being navigated too.
  if (event.currentTarget instanceof HTMLAnchorElement) {
    const url = event.currentTarget.href;
    return {
      ...linkClickedEventResult,
      nonPrivacySafeAttributes: {
        url
      }
    };
  } else {
    // We can't get the href from the event target, so dont include the url or any non privacy safe attributes
    return linkClickedEventResult;
  }
};
export const createLinkClickedPayloadNew = event => {
  // Through the `detail` property, we're able to determine if the event is (most likely) triggered via keyboard
  // https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail
  const isKeyboard = event.nativeEvent.detail === 0;
  const clickType = isKeyboard ? 'keyboard' : buttonMap.get(event.button);
  if (!clickType) {
    return;
  }
  const clickOutcome = getLinkClickOutcome(event, clickType);
  const keysHeld = getKeys(event);
  const defaultPrevented = event.defaultPrevented;

  // Check if the URL is a Confluence shortLink (contains "/l/cp/")
  let isConfluenceShortLink = false;
  if (event.currentTarget instanceof HTMLAnchorElement) {
    const url = event.currentTarget.href;
    isConfluenceShortLink = url.includes('/l/cp/');
  }
  const linkClickedEventResult = linkClickedEventWithShortLink({
    clickType,
    clickOutcome,
    keysHeld,
    defaultPrevented,
    isConfluenceShortLink
  });

  // if the current target is an anchor tag, we can get the href from it and use that as the url being navigated too.
  if (event.currentTarget instanceof HTMLAnchorElement) {
    const url = event.currentTarget.href;
    return {
      ...linkClickedEventResult,
      nonPrivacySafeAttributes: {
        url
      }
    };
  } else {
    // We can't get the href from the event target, so dont include the url or any non privacy safe attributes
    return linkClickedEventResult;
  }
};
export const createLinkClickedPayload = functionWithCondition(() => expValEquals('smart_link_confluence_short_link_analytics', 'cohort', 'test'),
// 12/17/2025: Clean up this feature gate once it's out in prod for 2 weeks - https://product-fabric.atlassian.net/browse/CCPERMS-5030
createLinkClickedPayloadNew, createLinkClickedPayloadOld);
export const fireLinkClickedEvent = createAnalyticsEvent => (event, overrides = {}) => {
  const payload = createLinkClickedPayload(event);
  if (payload) {
    createAnalyticsEvent({
      ...payload,
      ...overrides,
      attributes: {
        ...payload.attributes,
        ...(overrides === null || overrides === void 0 ? void 0 : overrides.attributes)
      },
      nonPrivacySafeAttributes: {
        ...payload.nonPrivacySafeAttributes,
        ...(overrides === null || overrides === void 0 ? void 0 : overrides.nonPrivacySafeAttributes)
      }
    }).fire(ANALYTICS_CHANNEL);
  }
};
const getDisplayName = WrappedComponent => {
  if (typeof WrappedComponent === 'string') {
    return WrappedComponent;
  }
  return WrappedComponent.displayName || WrappedComponent.name || 'Component';
};
export function withLinkClickedEvent(WrappedComponent) {
  const Component = props => {
    const onClick = useLinkClicked(props.onClick);
    const onMouseDown = useMouseDownEvent(props.onMouseDown);
    return /*#__PURE__*/React.createElement(WrappedComponent, {
      ...props,
      onClick,
      onMouseDown
    });
  };
  Component.displayName = `withLinkClickedEvent(${getDisplayName(WrappedComponent)})`;
  return Component;
}