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); }
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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
import React, { useCallback, useEffect, useMemo, useRef } from "react";
import useEngineContext from "../hooks/useEngineContext";

/** 长按触发的毫秒数 */
var LONG_PRESS_MS = 600;
/** 移动取消阈值（避免滚动被误识别为长按） */
var MOVE_CANCEL_PX = 8;
/** 兜底白名单（仅当插件不可用时使用，与 terra 的 DEFAULT_EDITABLE_FIELDS 同步） */
var FALLBACK_EDITABLE_FIELDS = ["variant", "className", "id", "style"];

/**
 * `ResponsiveEditWrapper` 入参
 */

/**
 * 编辑模式下包裹响应式组件，提供长按 → 弹出配置面板 的能力
 *
 * **运行时引用规则**：通过 `app.responsive.publishEditOpen(payload)` 发布事件，
 * **不直接 import 事件常量与 pubsub**；类型走 `import type`（编译期擦除）。
 *
 * 行为：
 *  - 仅在 `withResponsive` 检测到 `editMode === true` 时才会被使用；
 *  - 监听 pointerdown 启动 600ms 计时；pointermove（位移 > 8px）/ pointerup / pointercancel 取消；
 *  - 触发时 `e.preventDefault()` 阻止默认行为，再调用 `app.responsive.publishEditOpen(payload)` 通知面板；
 *  - 加 1px 虚线轮廓辅助识别。
 *
 * @example
 * <ResponsiveEditWrapper
 *   node={{ componentName: 'OrderItem', id: 'cart-1', className: 'order-item' }}
 *   finalProps={mergedProps}
 * >
 *   <OrderItem {...mergedProps} />
 * </ResponsiveEditWrapper>
 */
export var ResponsiveEditWrapper = function ResponsiveEditWrapper(_ref) {
  var _appHelper, _getApp;
  var children = _ref.children,
    node = _ref.node,
    finalProps = _ref.finalProps,
    editableFields = _ref.editableFields,
    as = _ref.as,
    className = _ref.className,
    style = _ref.style;
  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 || (_getApp = getApp()) === null || _getApp === void 0 ? void 0 : _getApp.app;
  var timerRef = useRef(null);
  var startPointRef = useRef(null);
  var cancel = useCallback(function () {
    if (timerRef.current != null) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }
    startPointRef.current = null;
  }, []);
  useEffect(function () {
    return function () {
      return cancel();
    };
  }, [cancel]);
  var handlePointerDown = useCallback(function (e) {
    cancel();
    startPointRef.current = {
      x: e.clientX,
      y: e.clientY
    };
    var ev = e.nativeEvent;
    timerRef.current = setTimeout(function () {
      var _plugin$getInfo$curre, _plugin$getInfo;
      timerRef.current = null;
      try {
        var _ev$preventDefault;
        (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 || _ev$preventDefault.call(ev);
      } catch (_unused) {
        /* noop */
      }
      // 通过 app 取插件实例（命令式入口）
      var plugin = app === null || app === void 0 ? void 0 : app.responsive;
      var currentBreakpoint = typeof (plugin === null || plugin === void 0 ? void 0 : plugin.getInfo) === "function" ? (_plugin$getInfo$curre = (_plugin$getInfo = plugin.getInfo()) === null || _plugin$getInfo === void 0 ? void 0 : _plugin$getInfo.currentBreakpoint) !== null && _plugin$getInfo$curre !== void 0 ? _plugin$getInfo$curre : "" : "";
      // 计算最终白名单：组件级 > 插件级（byNode/default）> 框架默认
      var fields = (typeof (plugin === null || plugin === void 0 ? void 0 : plugin.getEditableFieldsFor) === "function" ? plugin.getEditableFieldsFor(node, {
        extra: editableFields
      }) : undefined) || (editableFields && editableFields.length ? _toConsumableArray(editableFields) : [].concat(FALLBACK_EDITABLE_FIELDS));
      var payload = {
        componentName: node.componentName,
        id: node.id,
        className: node.className,
        props: finalProps,
        currentBreakpoint: currentBreakpoint,
        editableFields: fields
      };
      // 直接调用插件的发布方法，避免在主项目侧引用事件常量
      if (typeof (plugin === null || plugin === void 0 ? void 0 : plugin.publishEditOpen) === "function") {
        plugin.publishEditOpen(payload);
      }
    }, LONG_PRESS_MS);
  }, [app, cancel, node, finalProps, editableFields]);
  var handlePointerMove = useCallback(function (e) {
    var start = startPointRef.current;
    if (!start) return;
    var dx = e.clientX - start.x;
    var dy = e.clientY - start.y;
    if (Math.hypot(dx, dy) > MOVE_CANCEL_PX) cancel();
  }, [cancel]);
  var wrapperStyle = useMemo(function () {
    return _objectSpread({
      outline: "1px dashed rgba(24, 144, 255, 0.6)",
      outlineOffset: -1,
      cursor: "pointer",
      WebkitUserSelect: "none",
      userSelect: "none",
      WebkitTouchCallout: "none"
    }, style);
  }, [style]);
  var Tag = as || "div";
  return /*#__PURE__*/React.createElement(Tag, {
    className: className,
    style: wrapperStyle,
    onPointerDown: handlePointerDown,
    onPointerMove: handlePointerMove,
    onPointerUp: cancel,
    onPointerCancel: cancel,
    onPointerLeave: cancel,
    "data-responsive-edit": "1",
    "data-component-name": node.componentName || undefined,
    "data-component-id": node.id || undefined
  }, children);
};
export default ResponsiveEditWrapper;