"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useSmartCardActions = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _react = require("react");
var _linkExtractors = require("@atlaskit/link-extractors");
var _linkProvider = require("@atlaskit/link-provider");
var _linkingCommon = require("@atlaskit/linking-common");
var _outboundAuthFlowClient = require("@atlaskit/outbound-auth-flow-client");
var _platformFeatureFlags = require("@atlaskit/platform-feature-flags");
var _postMessageToPubsub = require("@atlaskit/rovo-triggers/post-message-to-pubsub");
var _expValEquals = require("@atlaskit/tmp-editor-statsig/exp-val-equals");
var _useAnalyticsEvents2 = require("../../common/analytics/generated/use-analytics-events");
var _constants = require("../../constants");
var _rovo = require("../../utils/rovo");
var _analytics = require("../analytics");
var _helpers = require("../helpers");
var _useActionFlags = _interopRequireDefault(require("../hooks/use-action-flags"));
var _useInvokeClientAction = _interopRequireDefault(require("../hooks/use-invoke-client-action"));
var _useResolve = _interopRequireDefault(require("../hooks/use-resolve"));
var POST_AUTH_CHAT_EXTENSION_KEY = 'google-object-provider';
// Smart Card resolver key differs from the consumer-facing Rovo payload key.
var POST_AUTH_CHAT_PAYLOAD_EXTENSION_KEY = 'google-drive';
var SMART_LINK_3P_POST_AUTH_SOURCE = 'smart-link-3p-post-auth';
var getPostAuthChatPayloadId = function getPostAuthChatPayloadId() {
  if (typeof crypto !== 'undefined') {
    if (typeof crypto.randomUUID === 'function') {
      return crypto.randomUUID();
    }
    if (typeof crypto.getRandomValues === 'function') {
      var values = new Uint32Array(4);
      crypto.getRandomValues(values);
      return "smart-link-post-auth-chat-".concat(Array.from(values, function (value) {
        return value.toString(16);
      }).join('-'));
    }
  }
  return "smart-link-post-auth-chat-".concat(Date.now());
};
var sendPostAuthChatOpenMessage = function sendPostAuthChatOpenMessage(url, documentTitle) {
  var _window$parent;
  if (typeof window === 'undefined' || typeof ((_window$parent = window.parent) === null || _window$parent === void 0 ? void 0 : _window$parent.postMessage) !== 'function') {
    return;
  }
  var payload = {
    type: 'chat-smartlink-3p-post-auth-launch',
    source: SMART_LINK_3P_POST_AUTH_SOURCE,
    openChat: true,
    openChatMode: 'mini-modal',
    data: {
      extensionKey: POST_AUTH_CHAT_PAYLOAD_EXTENSION_KEY,
      provider: 'Google Drive',
      projectContext: {
        projectId: url,
        projectName: documentTitle !== null && documentTitle !== void 0 ? documentTitle : 'Google Drive',
        projectUrl: url
      }
    }
  };
  window.parent.postMessage({
    eventType: _postMessageToPubsub.ROVO_POST_MESSAGE_EVENT_TYPE,
    payload: payload,
    payloadId: getPostAuthChatPayloadId()
  }, '*');
};
var useSmartCardActions = exports.useSmartCardActions = function useSmartCardActions(id, url) {
  var resolveUrl = (0, _useResolve.default)();
  var invokeClientAction = (0, _useInvokeClientAction.default)({});
  var _useAnalyticsEvents = (0, _useAnalyticsEvents2.useAnalyticsEvents)(),
    fireEvent = _useAnalyticsEvents.fireEvent;
  var flags = (0, _useActionFlags.default)();
  var _useSmartLinkContext = (0, _linkProvider.useSmartLinkContext)(),
    store = _useSmartLinkContext.store,
    rovoOptions = _useSmartLinkContext.rovoOptions;
  var rovoOptionsRef = (0, _react.useRef)(rovoOptions);
  rovoOptionsRef.current = rovoOptions;
  var getState = store.getState,
    dispatch = store.dispatch;
  var getSmartLinkState = (0, _react.useCallback)(function () {
    var _getState$url;
    var _ref = (_getState$url = getState()[url]) !== null && _getState$url !== void 0 ? _getState$url : {
        status: _constants.SmartLinkStatus.Pending
      },
      details = _ref.details,
      status = _ref.status,
      metadataStatus = _ref.metadataStatus;
    return {
      details: details,
      status: status,
      metadataStatus: metadataStatus
    };
  }, [getState, url]);
  var setMetadataStatus = (0, _react.useCallback)(function (metadataStatus) {
    dispatch((0, _linkingCommon.cardAction)(_linkingCommon.ACTION_UPDATE_METADATA_STATUS, {
      url: url
    }, undefined, undefined, metadataStatus));
  }, [dispatch, url]);

  // Original resolve function — signature kept intact for maximum safety when FG is off.
  var resolve = (0, _react.useCallback)( /*#__PURE__*/(0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee() {
    var resourceUrl,
      isReloading,
      isMetadataRequest,
      _args = arguments;
    return _regenerator.default.wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          resourceUrl = _args.length > 0 && _args[0] !== undefined ? _args[0] : url;
          isReloading = _args.length > 1 && _args[1] !== undefined ? _args[1] : false;
          isMetadataRequest = _args.length > 2 && _args[2] !== undefined ? _args[2] : false;
          return _context.abrupt("return", resolveUrl({
            url: resourceUrl,
            isReloading: isReloading,
            isMetadataRequest: isMetadataRequest,
            id: id
          }));
        case 1:
        case "end":
          return _context.stop();
      }
    }, _callee);
  })), [id, resolveUrl, url]);

  // New resolve function accepting ResolveUrlParams (minus 'id' which is closed over).
  // Used when FG is enabled to pass appearance to ORS.
  var resolveNew = (0, _react.useCallback)( /*#__PURE__*/(0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee2() {
    var params,
      _params$url,
      resourceUrl,
      _params$isReloading,
      isReloading,
      _params$isMetadataReq,
      isMetadataRequest,
      appearance,
      _args2 = arguments;
    return _regenerator.default.wrap(function (_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          params = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {};
          _params$url = params.url, resourceUrl = _params$url === void 0 ? url : _params$url, _params$isReloading = params.isReloading, isReloading = _params$isReloading === void 0 ? false : _params$isReloading, _params$isMetadataReq = params.isMetadataRequest, isMetadataRequest = _params$isMetadataReq === void 0 ? false : _params$isMetadataReq, appearance = params.appearance;
          return _context2.abrupt("return", resolveUrl({
            url: resourceUrl,
            isReloading: isReloading,
            isMetadataRequest: isMetadataRequest,
            id: id,
            appearance: appearance
          }));
        case 1:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  })), [id, resolveUrl, url]);

  /**
   * Register a smart link for resolution.
   * @param appearance - Card appearance hint for ORS to optimize response payload.
   *                     When 'inline', ORS returns minimal data (title, status).
   *                     When 'block' or 'embed', ORS returns full data including summary.
   */
  var register = (0, _react.useCallback)(function (appearance) {
    var _getSmartLinkState = getSmartLinkState(),
      details = _getSmartLinkState.details;
    if (!details) {
      dispatch((0, _linkingCommon.cardAction)(_linkingCommon.ACTION_RESOLVING, {
        url: url
      }));
      // Always set metadataStatus to 'pending' during registration to prevent
      // loadMetadata from firing a duplicate concurrent fetch if a hover card
      // mounts while registration is in-flight. This matches pre-PR behaviour.
      setMetadataStatus('pending');
    }
    if ((0, _platformFeatureFlags.fg)('platform_smartlink_inline_resolve_optimization')) {
      return resolveNew({
        url: url,
        appearance: appearance
      });
    }
    return resolve(url);
  }, [getSmartLinkState, resolve, resolveNew, dispatch, url, setMetadataStatus]);
  var reload = (0, _react.useCallback)(function (appearance) {
    var _getSmartLinkState2 = getSmartLinkState(),
      details = _getSmartLinkState2.details;
    var definitionId = (0, _helpers.getDefinitionId)(details);
    if ((0, _platformFeatureFlags.fg)('platform_smartlink_inline_resolve_optimization')) {
      if (definitionId) {
        (0, _helpers.getByDefinitionId)(definitionId, getState()).map(function (reloadUrl) {
          return resolveNew({
            url: reloadUrl,
            isReloading: true,
            appearance: appearance
          });
        });
      } else {
        resolveNew({
          url: url,
          isReloading: true,
          appearance: appearance
        });
      }
    } else {
      if (definitionId) {
        (0, _helpers.getByDefinitionId)(definitionId, getState()).map(function (reloadUrl) {
          return resolve(reloadUrl, true);
        });
      } else {
        resolve(url, true);
      }
    }
  }, [getSmartLinkState, url, getState, resolve, resolveNew]);

  /**
   * Load metadata for hover card preview.
   * This always requests 'block' appearance to get full data including summary.
   *
   * Inline optimized and SSR-resolved links keep metadataStatus pending until hover
   * requests the full block response.
   */
  var loadMetadata = (0, _react.useCallback)(function () {
    var _getSmartLinkState3 = getSmartLinkState(),
      metadataStatus = _getSmartLinkState3.metadataStatus;
    var needsBlockData = metadataStatus === undefined || metadataStatus === 'pending' && (0, _platformFeatureFlags.fg)('platform_smartlink_inline_resolve_optimization');
    if (needsBlockData) {
      setMetadataStatus('pending');
      if ((0, _platformFeatureFlags.fg)('platform_smartlink_inline_resolve_optimization')) {
        // Always request 'block' appearance for hover card metadata to get full data
        return resolveNew({
          url: url,
          isMetadataRequest: true,
          appearance: 'block'
        });
      }
      return resolve(url, false, true);
    }
  }, [getSmartLinkState, resolve, resolveNew, setMetadataStatus, url]);
  var authorize = (0, _react.useCallback)(function (appearance) {
    var _getSmartLinkState4 = getSmartLinkState(),
      details = _getSmartLinkState4.details,
      status = _getSmartLinkState4.status;
    var definitionId = (0, _helpers.getDefinitionId)(details);
    var extensionKey = (0, _helpers.getExtensionKey)(details);
    var isSupportedPostAuthChatExtensionKey = extensionKey === POST_AUTH_CHAT_EXTENSION_KEY;
    var services = (0, _helpers.getServices)(details);
    // When authentication is triggered, let GAS know!
    if (status === 'unauthorized') {
      fireEvent('ui.button.clicked.connectAccount', {
        display: appearance,
        definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null
      });
    }
    if (status === 'forbidden') {
      fireEvent('ui.smartLink.clicked.tryAnotherAccount', {
        display: appearance,
        definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null
      });
    }
    if (services.length > 0) {
      fireEvent('screen.consentModal.viewed', {
        definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null
      });
      (0, _outboundAuthFlowClient.auth)(services[0].url).then(function () {
        fireEvent('track.applicationAccount.connected', {
          definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null
        });
        (0, _analytics.startUfoExperience)('smart-link-authenticated', id, {
          extensionKey: extensionKey,
          status: 'success'
        });
        fireEvent('operational.smartLink.connectSucceeded', {
          definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null
        });

        // Post-auth Chat onboarding: auto-open Rovo Chat mini-modal with the
        // authed 3P link as context, for supported providers (e.g. Google Drive).
        // Provider eligibility is derived from the pre-auth SmartLink state.
        var isEligibleForPostAuthChat = status === 'unauthorized' && isSupportedPostAuthChatExtensionKey && (0, _platformFeatureFlags.fg)('platform_sl_3p_post_auth_chat_open_fg') && (0, _rovo.getIsRovoChatEnabled)(rovoOptionsRef.current);

        // Experiment check: fires exposure for both control and treatment.
        // Only reached after eligibility preconditions + kill switch pass, so
        // exposure is counted for the triggered eligible pool.
        var isPostAuthChatTreatment = isEligibleForPostAuthChat && (0, _expValEquals.expValEquals)('platform_sl_3p_post_auth_chat_open_exp', 'isEnabled', true);
        if (status === 'unauthorized' && !isPostAuthChatTreatment) {
          var provider = (0, _linkExtractors.extractSmartLinkProvider)(details);
          flags.showConnectFlag({
            id: "smart-link-connect-success-".concat(extensionKey),
            provider: provider
          });
        }
        reload();
        if (isPostAuthChatTreatment) {
          sendPostAuthChatOpenMessage(url, (0, _linkExtractors.extractSmartLinkTitle)(details));
        }
      }, function (err) {
        var _err$type;
        (0, _analytics.startUfoExperience)('smart-link-authenticated', id, {
          extensionKey: extensionKey,
          status: err.type
        });
        fireEvent('operational.smartLink.connectFailed', {
          definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null,
          reason: (_err$type = err.type) !== null && _err$type !== void 0 ? _err$type : null
        });
        if (err.type === 'auth_window_closed') {
          fireEvent('ui.consentModal.closed', {
            display: appearance,
            definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null
          });
        }
        reload();
      });
    }
  }, [getSmartLinkState, id, reload, fireEvent, flags, url]);
  var invoke = (0, _react.useCallback)( /*#__PURE__*/function () {
    var _ref4 = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee3(opts, appearance) {
      var key, action, source;
      return _regenerator.default.wrap(function (_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            key = opts.key, action = opts.action;
            source = opts.source || appearance;
            if (!(opts.type === 'client')) {
              _context3.next = 2;
              break;
            }
            _context3.next = 1;
            return invokeClientAction({
              actionFn: opts.action.promise,
              actionType: action.type,
              display: source,
              extensionKey: key
            });
          case 1:
            return _context3.abrupt("return", _context3.sent);
          case 2:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    }));
    return function (_x, _x2) {
      return _ref4.apply(this, arguments);
    };
  }(), [invokeClientAction]);
  return (0, _react.useMemo)(function () {
    return {
      register: register,
      reload: reload,
      authorize: authorize,
      invoke: invoke,
      loadMetadata: loadMetadata
    };
  }, [register, reload, authorize, invoke, loadMetadata]);
};