import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import { useCallback, useMemo, useRef } from 'react';
import { extractSmartLinkProvider, extractSmartLinkTitle } from '@atlaskit/link-extractors';
import { useSmartLinkContext } from '@atlaskit/link-provider';
import { ACTION_RESOLVING, ACTION_UPDATE_METADATA_STATUS, cardAction } from '@atlaskit/linking-common';
import { auth } from '@atlaskit/outbound-auth-flow-client';
import { fg } from '@atlaskit/platform-feature-flags';
import { ROVO_POST_MESSAGE_EVENT_TYPE } from '@atlaskit/rovo-triggers/post-message-to-pubsub';
import { expValEquals } from '@atlaskit/tmp-editor-statsig/exp-val-equals';
import { useAnalyticsEvents } from '../../common/analytics/generated/use-analytics-events';
import { SmartLinkStatus } from '../../constants';
import { getIsRovoChatEnabled } from '../../utils/rovo';
import { startUfoExperience } from '../analytics';
import { getByDefinitionId, getDefinitionId, getExtensionKey, getServices } from '../helpers';
import useActionFlags from '../hooks/use-action-flags';
import useInvokeClientAction from '../hooks/use-invoke-client-action';
import useResolve from '../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: ROVO_POST_MESSAGE_EVENT_TYPE,
    payload: payload,
    payloadId: getPostAuthChatPayloadId()
  }, '*');
};
export var useSmartCardActions = function useSmartCardActions(id, url) {
  var resolveUrl = useResolve();
  var invokeClientAction = useInvokeClientAction({});
  var _useAnalyticsEvents = useAnalyticsEvents(),
    fireEvent = _useAnalyticsEvents.fireEvent;
  var flags = useActionFlags();
  var _useSmartLinkContext = useSmartLinkContext(),
    store = _useSmartLinkContext.store,
    rovoOptions = _useSmartLinkContext.rovoOptions;
  var rovoOptionsRef = useRef(rovoOptions);
  rovoOptionsRef.current = rovoOptions;
  var getState = store.getState,
    dispatch = store.dispatch;
  var getSmartLinkState = useCallback(function () {
    var _getState$url;
    var _ref = (_getState$url = getState()[url]) !== null && _getState$url !== void 0 ? _getState$url : {
        status: SmartLinkStatus.Pending
      },
      details = _ref.details,
      status = _ref.status,
      metadataStatus = _ref.metadataStatus;
    return {
      details: details,
      status: status,
      metadataStatus: metadataStatus
    };
  }, [getState, url]);
  var setMetadataStatus = useCallback(function (metadataStatus) {
    dispatch(cardAction(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 = useCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var resourceUrl,
      isReloading,
      isMetadataRequest,
      _args = arguments;
    return _regeneratorRuntime.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 = useCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
    var params,
      _params$url,
      resourceUrl,
      _params$isReloading,
      isReloading,
      _params$isMetadataReq,
      isMetadataRequest,
      appearance,
      _args2 = arguments;
    return _regeneratorRuntime.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 = useCallback(function (appearance) {
    var _getSmartLinkState = getSmartLinkState(),
      details = _getSmartLinkState.details;
    if (!details) {
      dispatch(cardAction(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 (fg('platform_smartlink_inline_resolve_optimization')) {
      return resolveNew({
        url: url,
        appearance: appearance
      });
    }
    return resolve(url);
  }, [getSmartLinkState, resolve, resolveNew, dispatch, url, setMetadataStatus]);
  var reload = useCallback(function (appearance) {
    var _getSmartLinkState2 = getSmartLinkState(),
      details = _getSmartLinkState2.details;
    var definitionId = getDefinitionId(details);
    if (fg('platform_smartlink_inline_resolve_optimization')) {
      if (definitionId) {
        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) {
        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 = useCallback(function () {
    var _getSmartLinkState3 = getSmartLinkState(),
      metadataStatus = _getSmartLinkState3.metadataStatus;
    var needsBlockData = metadataStatus === undefined || metadataStatus === 'pending' && fg('platform_smartlink_inline_resolve_optimization');
    if (needsBlockData) {
      setMetadataStatus('pending');
      if (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 = useCallback(function (appearance) {
    var _getSmartLinkState4 = getSmartLinkState(),
      details = _getSmartLinkState4.details,
      status = _getSmartLinkState4.status;
    var definitionId = getDefinitionId(details);
    var extensionKey = getExtensionKey(details);
    var isSupportedPostAuthChatExtensionKey = extensionKey === POST_AUTH_CHAT_EXTENSION_KEY;
    var services = 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
      });
      auth(services[0].url).then(function () {
        fireEvent('track.applicationAccount.connected', {
          definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null
        });
        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 && fg('platform_sl_3p_post_auth_chat_open_fg') && 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 && expValEquals('platform_sl_3p_post_auth_chat_open_exp', 'isEnabled', true);
        if (status === 'unauthorized' && !isPostAuthChatTreatment) {
          var provider = extractSmartLinkProvider(details);
          flags.showConnectFlag({
            id: "smart-link-connect-success-".concat(extensionKey),
            provider: provider
          });
        }
        reload();
        if (isPostAuthChatTreatment) {
          sendPostAuthChatOpenMessage(url, extractSmartLinkTitle(details));
        }
      }, function (err) {
        var _err$type;
        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 = useCallback( /*#__PURE__*/function () {
    var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(opts, appearance) {
      var key, action, source;
      return _regeneratorRuntime.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 useMemo(function () {
    return {
      register: register,
      reload: reload,
      authorize: authorize,
      invoke: invoke,
      loadMetadata: loadMetadata
    };
  }, [register, reload, authorize, invoke, loadMetadata]);
};