function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
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) { _defineProperty(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; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
import React, { useContext, useMemo } from "react";
import useEngineContext from "../hooks/useEngineContext";
import ResponsiveEditWrapper from "./ResponsiveEditWrapper";
var FALLBACK_RESPONSIVE_INFO = {
  currentBreakpoint: "",
  deviceType: ""
};
var FallbackResponsiveOverrideContext = /*#__PURE__*/React.createContext(null);
function useFallbackResponsive() {
  return FALLBACK_RESPONSIVE_INFO;
}

/**
 * 用 `withResponsive` 包裹任意 React 组件，使其自动获得：
 *  - 响应式 variant 注入：默认 `variant = currentBreakpoint`，规则可覆盖；
 *  - 全局 / 本地覆写规则注入：按 nodeType+nodeId+when 命中后浅合并 props；
 *  - 编辑模式长按编辑：`editMode === true` 时自动套 `ResponsiveEditWrapper`。
 *
 * **运行时引用规则**：所有 React 资产（`useResponsive` / `ResponsiveOverrideContext`）
 * 都通过 `app.responsive.{hooks,components}` 命名空间访问，**不直接 import @terra 实体**；
 * 仅类型走 `import type` 走 @terra（编译期擦除）。
 *
 * 由于 `withResponsive` 是纯函数工厂，模块顶层调用 0 副作用；hook/Context 取值发生在
 * 组件渲染期，那时 `app.responsive` 必已就绪（terra/bootstrap 同步注册）。
 *
 * @example
 * interface OrderItemProps extends BaseResponsiveProps {
 *   title: string;
 * }
 * const OrderItem: React.FC<OrderItemProps> = ({ title, variant, className }) => (
 *   <div className={className}>
 *     {variant === 'phone' ? <span>{title}</span> : <strong>{title}</strong>}
 *   </div>
 * );
 * OrderItem.displayName = 'OrderItem';
 * export default withResponsive(OrderItem);
 */

export function withResponsive(Component, options) {
  var inferredName = (options === null || options === void 0 ? void 0 : options.name) || Component.displayName || Component.name || "ResponsiveComponent";
  var ComponentWithRef = Component;
  var Wrapped = /*#__PURE__*/React.forwardRef(function (rawProps, ref) {
    var _appHelper, _responsive$hooks, _responsive$component;
    var context = useEngineContext();
    var getApp = context === null || context === void 0 || (_appHelper = context.appHelper) === null || _appHelper === void 0 || (_appHelper = _appHelper.utils) === null || _appHelper === void 0 ? void 0 : _appHelper.getApp;
    var app = getApp === null || getApp === void 0 ? void 0 : getApp();
    // 命令式入口：通过 app 取插件实例（terra/bootstrap 同步注册，渲染期间一定存在）
    var responsive = app === null || app === void 0 ? void 0 : app.responsive;
    // 命名空间取 hook 与 Context（模块加载期固化的稳定引用）
    var useResponsiveHook = typeof (responsive === null || responsive === void 0 || (_responsive$hooks = responsive.hooks) === null || _responsive$hooks === void 0 ? void 0 : _responsive$hooks.useResponsive) === "function" ? responsive.hooks.useResponsive : useFallbackResponsive;
    var ResponsiveOverrideContext = responsive === null || responsive === void 0 || (_responsive$component = responsive.components) === null || _responsive$component === void 0 ? void 0 : _responsive$component.ResponsiveOverrideContext;
    var ResponsiveOverrideCtx = ResponsiveOverrideContext && _typeof(ResponsiveOverrideContext) === "object" ? ResponsiveOverrideContext : FallbackResponsiveOverrideContext;
    var info = useResponsiveHook() || FALLBACK_RESPONSIVE_INFO;
    var overrideCtx = useContext(ResponsiveOverrideCtx);
    var node = useMemo(function () {
      return {
        componentName: inferredName,
        id: rawProps.id,
        className: rawProps.className
      };
    }, [rawProps.id, rawProps.className]);

    // 解析最终 props：优先走 Context 的 resolveProps（与 Provider 同源），其次走插件直调
    var finalProps = useMemo(function () {
      if (overrideCtx !== null && overrideCtx !== void 0 && overrideCtx.resolveProps) {
        return overrideCtx.resolveProps(node, rawProps);
      }
      if (typeof (responsive === null || responsive === void 0 ? void 0 : responsive.resolveProps) === "function") {
        return responsive.resolveProps(node, rawProps);
      }
      // 兜底：未挂 Provider 时仍注入默认 variant
      var next = _objectSpread({}, rawProps);
      if (typeof next.variant !== "string" || next.variant.length === 0) {
        next.variant = info.currentBreakpoint || info.deviceType;
      }
      return next;
    }, [overrideCtx, responsive, node, rawProps, info.currentBreakpoint, info.deviceType]);
    var enableEdit = (options === null || options === void 0 ? void 0 : options.editable) !== false && !!(overrideCtx !== null && overrideCtx !== void 0 && overrideCtx.editMode);
    if (enableEdit) {
      return /*#__PURE__*/React.createElement(ResponsiveEditWrapper, {
        node: node,
        finalProps: finalProps,
        editableFields: options === null || options === void 0 ? void 0 : options.editableFields
      }, /*#__PURE__*/React.createElement(ComponentWithRef, _extends({}, finalProps, {
        ref: ref
      })));
    }
    return /*#__PURE__*/React.createElement(ComponentWithRef, _extends({}, finalProps, {
      ref: ref
    }));
  });
  Wrapped.displayName = "withResponsive(".concat(inferredName, ")");
  return Wrapped;
}
export default withResponsive;