"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getKeys = exports.fireLinkClickedEvent = exports.createLinkClickedPayloadOld = exports.createLinkClickedPayloadNew = exports.createLinkClickedPayload = exports.buttonMap = void 0;
exports.getLinkClickOutcome = getLinkClickOutcome;
exports.withLinkClickedEvent = withLinkClickedEvent;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireDefault(require("react"));
var _userAgent = require("@atlaskit/linking-common/user-agent");
var _platformFeatureFlagsReact = require("@atlaskit/platform-feature-flags-react");
var _expValEquals = require("@atlaskit/tmp-editor-statsig/exp-val-equals");
var _useLinkClicked = require("../../state/analytics/useLinkClicked");
var _analytics = require("./analytics");
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var buttonMap = exports.buttonMap = new Map([[undefined, 'none'], [0, 'left'], [1, 'middle'], [2, 'right']]);
var getKeys = exports.getKeys = function getKeys(e) {
  return ['alt', 'ctrl', 'meta', 'shift'].filter(function (key) {
    return e["".concat(key, "Key")] === true;
  });
};
var isContentEditable = function isContentEditable(el) {
  return el instanceof HTMLElement && el.isContentEditable;
};
function getLinkClickOutcome(e, clickType) {
  var _browser = (0, _userAgent.browser)(),
    mac = _browser.mac,
    safari = _browser.safari;

  /**
   * 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';
        }
        var target = e.currentTarget.getAttribute('target');
        if (target === '_blank') {
          return 'clickThroughNewTabOrWindow';
        }
        return 'clickThrough';
      }
    case 'middle':
      {
        return 'clickThroughNewTabOrWindow';
      }
    case 'right':
      {
        return 'contextMenu';
      }
  }
  return 'unknown';
}
var linkClickedEventOld = function linkClickedEventOld(_ref) {
  var clickType = _ref.clickType,
    clickOutcome = _ref.clickOutcome,
    keysHeld = _ref.keysHeld,
    defaultPrevented = _ref.defaultPrevented;
  return {
    action: 'clicked',
    actionSubject: 'link',
    eventType: 'ui',
    attributes: {
      clickType: clickType,
      clickOutcome: clickOutcome,
      keysHeld: keysHeld,
      defaultPrevented: defaultPrevented
    }
  };
};
var linkClickedEventWithShortLink = function linkClickedEventWithShortLink(_ref2) {
  var clickType = _ref2.clickType,
    clickOutcome = _ref2.clickOutcome,
    keysHeld = _ref2.keysHeld,
    defaultPrevented = _ref2.defaultPrevented,
    isConfluenceShortLink = _ref2.isConfluenceShortLink;
  return {
    action: 'clicked',
    actionSubject: 'link',
    eventType: 'ui',
    attributes: {
      clickType: clickType,
      clickOutcome: clickOutcome,
      keysHeld: keysHeld,
      defaultPrevented: defaultPrevented,
      isConfluenceShortLink: isConfluenceShortLink
    }
  };
};
var createLinkClickedPayloadOld = exports.createLinkClickedPayloadOld = function 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
  var isKeyboard = event.nativeEvent.detail === 0;
  var clickType = isKeyboard ? 'keyboard' : buttonMap.get(event.button);
  if (!clickType) {
    return;
  }
  var clickOutcome = getLinkClickOutcome(event, clickType);
  var keysHeld = getKeys(event);
  var defaultPrevented = event.defaultPrevented;
  var linkClickedEventResult = linkClickedEventOld({
    clickType: clickType,
    clickOutcome: clickOutcome,
    keysHeld: keysHeld,
    defaultPrevented: 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) {
    var url = event.currentTarget.href;
    return _objectSpread(_objectSpread({}, linkClickedEventResult), {}, {
      nonPrivacySafeAttributes: {
        url: 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;
  }
};
var createLinkClickedPayloadNew = exports.createLinkClickedPayloadNew = function 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
  var isKeyboard = event.nativeEvent.detail === 0;
  var clickType = isKeyboard ? 'keyboard' : buttonMap.get(event.button);
  if (!clickType) {
    return;
  }
  var clickOutcome = getLinkClickOutcome(event, clickType);
  var keysHeld = getKeys(event);
  var defaultPrevented = event.defaultPrevented;

  // Check if the URL is a Confluence shortLink (contains "/l/cp/")
  var isConfluenceShortLink = false;
  if (event.currentTarget instanceof HTMLAnchorElement) {
    var url = event.currentTarget.href;
    isConfluenceShortLink = url.includes('/l/cp/');
  }
  var linkClickedEventResult = linkClickedEventWithShortLink({
    clickType: clickType,
    clickOutcome: clickOutcome,
    keysHeld: keysHeld,
    defaultPrevented: defaultPrevented,
    isConfluenceShortLink: 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) {
    var _url = event.currentTarget.href;
    return _objectSpread(_objectSpread({}, linkClickedEventResult), {}, {
      nonPrivacySafeAttributes: {
        url: _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;
  }
};
var createLinkClickedPayload = exports.createLinkClickedPayload = (0, _platformFeatureFlagsReact.functionWithCondition)(function () {
  return (0, _expValEquals.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);
var fireLinkClickedEvent = exports.fireLinkClickedEvent = function fireLinkClickedEvent(createAnalyticsEvent) {
  return function (event) {
    var overrides = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    var payload = createLinkClickedPayload(event);
    if (payload) {
      createAnalyticsEvent(_objectSpread(_objectSpread(_objectSpread({}, payload), overrides), {}, {
        attributes: _objectSpread(_objectSpread({}, payload.attributes), overrides === null || overrides === void 0 ? void 0 : overrides.attributes),
        nonPrivacySafeAttributes: _objectSpread(_objectSpread({}, payload.nonPrivacySafeAttributes), overrides === null || overrides === void 0 ? void 0 : overrides.nonPrivacySafeAttributes)
      })).fire(_analytics.ANALYTICS_CHANNEL);
    }
  };
};
var getDisplayName = function getDisplayName(WrappedComponent) {
  if (typeof WrappedComponent === 'string') {
    return WrappedComponent;
  }
  return WrappedComponent.displayName || WrappedComponent.name || 'Component';
};
function withLinkClickedEvent(WrappedComponent) {
  var Component = function Component(props) {
    var onClick = (0, _useLinkClicked.useLinkClicked)(props.onClick);
    var onMouseDown = (0, _useLinkClicked.useMouseDownEvent)(props.onMouseDown);
    return /*#__PURE__*/_react.default.createElement(WrappedComponent, _objectSpread(_objectSpread({}, props), {}, {
      onClick: onClick,
      onMouseDown: onMouseDown
    }));
  };
  Component.displayName = "withLinkClickedEvent(".concat(getDisplayName(WrappedComponent), ")");
  return Component;
}