function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
/**
 * FloorMapEditTopBar - 编辑态顶栏
 * - `mode="compact"`：画布 Tab + 可选 `canvasTabsBarTrailing`（全屏入口在左下 Dock）
 * - `mode="full"`：画布 Tab + `canvasTabsBarTrailing` + 保存（仅非浏览器全屏时）+ 扩展操作
 */
import React, { useCallback, useMemo } from 'react';
import classNames from 'classnames';
import { Button, Modal } from 'antd';
import { RedoHistoryIcon, UndoHistoryIcon } from "./HistoryIcons";
import { locales } from '@pisell/utils';
import useEngineContext from "../../../hooks/useEngineContext";
import { initFloorMapLayoutLocales } from "../utils/floorMapCanvasDisplay";
import { CanvasTabs } from "./CanvasTabs";
import "./FloorMapEditTopBar.less";
var PREFIX = 'pisell-floor-map-layout';
var I18N_TB = 'pisell-floor-map-layout.edit-top-bar';
/** 检测 macOS / iPad，决定快捷键提示用 ⌘ 还是 Ctrl */
function detectIsMacLike() {
  if (typeof navigator === 'undefined') return false;
  var p = navigator.platform || '';
  var ua = navigator.userAgent || '';
  return /Mac|iPhone|iPad|iPod/i.test(p) || /Macintosh/i.test(ua);
}
export function FloorMapEditTopBar(props) {
  var _engineCtx$engine;
  var _props$mode = props.mode,
    mode = _props$mode === void 0 ? 'full' : _props$mode,
    config = props.config,
    canvases = props.canvases,
    currentCanvasId = props.currentCanvasId,
    onTabChange = props.onTabChange,
    _props$canEditTabs = props.canEditTabs,
    canEditTabs = _props$canEditTabs === void 0 ? false : _props$canEditTabs,
    onAddCanvas = props.onAddCanvas,
    onRemoveCanvas = props.onRemoveCanvas,
    onRenameCanvas = props.onRenameCanvas,
    onSave = props.onSave,
    saving = props.saving,
    saveError = props.saveError,
    layoutDirty = props.layoutDirty,
    _props$isFullscreen = props.isFullscreen,
    isFullscreen = _props$isFullscreen === void 0 ? false : _props$isFullscreen,
    extraActions = props.extraActions,
    canvasTabsBarTrailing = props.canvasTabsBarTrailing,
    _props$hideCanvasTabs = props.hideCanvasTabs,
    hideCanvasTabs = _props$hideCanvasTabs === void 0 ? false : _props$hideCanvasTabs,
    onUndo = props.onUndo,
    onRedo = props.onRedo,
    _props$canUndo = props.canUndo,
    canUndo = _props$canUndo === void 0 ? false : _props$canUndo,
    _props$canRedo = props.canRedo,
    canRedo = _props$canRedo === void 0 ? false : _props$canRedo,
    onExitEdit = props.onExitEdit,
    onCancelEdit = props.onCancelEdit,
    className = props.className,
    _props$phoneLayout = props.phoneLayout,
    phoneLayout = _props$phoneLayout === void 0 ? false : _props$phoneLayout;
  var engineCtx = useEngineContext();
  var engineLocale = (engineCtx === null || engineCtx === void 0 || (_engineCtx$engine = engineCtx.engine) === null || _engineCtx$engine === void 0 || (_engineCtx$engine = _engineCtx$engine.props) === null || _engineCtx$engine === void 0 ? void 0 : _engineCtx$engine.locale) || 'zh-CN';
  var topBarLabels = useMemo(function () {
    initFloorMapLayoutLocales(engineLocale);
    return {
      aria: locales.getText("".concat(I18N_TB, ".aria")),
      unsaved: locales.getText("".concat(I18N_TB, ".unsaved")),
      save: locales.getText("".concat(I18N_TB, ".save")),
      saving: locales.getText("".concat(I18N_TB, ".saving")),
      undo: locales.getText("".concat(I18N_TB, ".undo")),
      redo: locales.getText("".concat(I18N_TB, ".redo")),
      cancelEdit: locales.getText("".concat(I18N_TB, ".cancel-edit")),
      finishEdit: locales.getText("".concat(I18N_TB, ".finish-edit")),
      cancelConfirmTitle: locales.getText("".concat(I18N_TB, ".cancel-confirm-title")),
      cancelConfirmContent: locales.getText("".concat(I18N_TB, ".cancel-confirm-content")),
      cancelConfirmOk: locales.getText("".concat(I18N_TB, ".cancel-confirm-ok")),
      cancelConfirmCancel: locales.getText("".concat(I18N_TB, ".cancel-confirm-cancel"))
    };
  }, [engineLocale]);
  var showHistory = Boolean(onUndo || onRedo);
  /** 历史按钮组（撤销/重做）：full、compact 共用同一段渲染 */
  var historyGroup = useMemo(function () {
    if (!showHistory) return null;
    var isMac = detectIsMacLike();
    var cmd = isMac ? '⌘' : 'Ctrl';
    var undoTitle = "".concat(topBarLabels.undo, " (").concat(cmd, "+Z)");
    var redoTitle = "".concat(topBarLabels.redo, " (").concat(cmd, "+Shift+Z)");
    return /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "-edit-top-bar-history"),
      role: "group",
      "aria-label": "".concat(topBarLabels.undo, " / ").concat(topBarLabels.redo)
    }, /*#__PURE__*/React.createElement(Button, {
      type: "text",
      size: "small",
      className: "".concat(PREFIX, "-edit-top-bar-history-btn"),
      icon: /*#__PURE__*/React.createElement(UndoHistoryIcon, null),
      disabled: !canUndo,
      onClick: onUndo,
      "aria-label": undoTitle
    }, topBarLabels.undo), /*#__PURE__*/React.createElement(Button, {
      type: "text",
      size: "small",
      className: "".concat(PREFIX, "-edit-top-bar-history-btn"),
      icon: /*#__PURE__*/React.createElement(RedoHistoryIcon, null),
      disabled: !canRedo,
      onClick: onRedo,
      "aria-label": redoTitle
    }, topBarLabels.redo));
  }, [showHistory, topBarLabels.undo, topBarLabels.redo, canUndo, canRedo, onUndo, onRedo]);

  /** 浏览器全屏时顶栏不展示保存，改由侧栏承担（见 PisellFloorMapLayout 对 Toolbar onSave 的互斥逻辑） */
  var showSave = Boolean(onSave && config.canvasUi.canEdit) && !isFullscreen;
  /**
   * 业务层提供 onExitEdit 时改用「取消编辑 + 完成」组合，
   * 此时不再展示独立的「保存」按钮（完成 = 保存 + 退出，避免冗余）。
   */
  var showExitGroup = Boolean(onExitEdit && config.canvasUi.canEdit);

  /**
   * 「未保存」徽章独立成一段：放到 undo / redo 左边，与「编辑历史」视觉上同属一个状态区。
   * 触发条件保持原样：必须 layoutDirty 且当前确实有保存通道（showSave 或 showExitGroup），
   * 否则纯阅读态出现「未保存」会让用户困惑。
   */
  var dirtyBadge = layoutDirty && (showExitGroup || showSave) ? /*#__PURE__*/React.createElement("span", {
    className: "".concat(PREFIX, "-edit-top-bar-dirty-badge"),
    role: "status",
    "aria-live": "polite"
  }, topBarLabels.unsaved) : null;

  /**
   * 取消编辑：layoutDirty 时弹二次确认，避免误触丢失草稿；
   * 干净状态直接走原本的退出路径，不打扰用户。
   * onOk 里复用「优先 onCancelEdit，回退 onExitEdit」的语义，与保存按钮链路对称。
   *
   * 走 {@link Modal.useModal} 拿到的实例 + 同级渲染的 `modalContextHolder`，确保：
   * - OK 按钮颜色继承当前 ConfigProvider 主题主色（静态 `Modal.confirm` 不会继承）；
   * - 不依赖外层是否包了 PisellConfigProvider/`App` —— 这个组件可能被低代码引擎
   *   单独挂在画布层，并不一定有上述 Provider，原先走 `PisellModal.confirm`
   *   会因为 `setModal` 没被调用拿到 `undefined.confirm` 直接抛错。
   */
  var _Modal$useModal = Modal.useModal(),
    _Modal$useModal2 = _slicedToArray(_Modal$useModal, 2),
    modalApi = _Modal$useModal2[0],
    modalContextHolder = _Modal$useModal2[1];
  var performCancel = useCallback(function () {
    if (onCancelEdit) onCancelEdit();else onExitEdit === null || onExitEdit === void 0 || onExitEdit();
  }, [onCancelEdit, onExitEdit]);
  var handleCancelClick = useCallback(function () {
    if (!layoutDirty) {
      performCancel();
      return;
    }
    modalApi.confirm({
      title: topBarLabels.cancelConfirmTitle,
      content: topBarLabels.cancelConfirmContent,
      okText: topBarLabels.cancelConfirmOk,
      cancelText: topBarLabels.cancelConfirmCancel,
      onOk: function onOk() {
        return performCancel();
      },
      autoFocusButton: 'cancel'
    });
  }, [layoutDirty, performCancel, modalApi, topBarLabels.cancelConfirmTitle, topBarLabels.cancelConfirmContent, topBarLabels.cancelConfirmOk, topBarLabels.cancelConfirmCancel]);
  var hasTrailing = canvasTabsBarTrailing != null && canvasTabsBarTrailing !== false;
  var hasFullActions = showSave || showExitGroup || Boolean(saveError) || extraActions != null && extraActions !== false || hasTrailing || showHistory;
  var tabsHiddenClass = hideCanvasTabs ? "".concat(PREFIX, "-edit-top-bar--tabs-hidden") : undefined;
  if (mode === 'compact') {
    var showCompactActions = hasTrailing || showHistory;
    var tabsInner = /*#__PURE__*/React.createElement(CanvasTabs, {
      canvases: canvases,
      currentCanvasId: currentCanvasId,
      onTabChange: onTabChange,
      canEdit: canEditTabs,
      onAddCanvas: onAddCanvas,
      onRemoveCanvas: onRemoveCanvas,
      onRenameCanvas: onRenameCanvas,
      className: "".concat(PREFIX, "-edit-top-bar-canvas-tabs")
    });
    var actionsInner = /*#__PURE__*/React.createElement(React.Fragment, null, historyGroup, canvasTabsBarTrailing);
    /**
     * 手机：第一行与阅读态相同（`read-canvas-tabs-bar` + 仅 CanvasTabs），
     * 撤销/图例等放第二行，且左对齐（非居中）。
     * 桌面：单行与阅读态相同结构（左 Tabs 右操作）。
     */
    if (phoneLayout) {
      return /*#__PURE__*/React.createElement(React.Fragment, null, !hideCanvasTabs ? /*#__PURE__*/React.createElement("div", {
        className: classNames("".concat(PREFIX, "-edit-top-bar"), "".concat(PREFIX, "-read-canvas-tabs-bar"), "".concat(PREFIX, "-edit-top-bar--compact"), "".concat(PREFIX, "-edit-top-bar--phone-edit-canvas-row"), className),
        role: "toolbar",
        "aria-label": topBarLabels.aria
      }, /*#__PURE__*/React.createElement("div", {
        className: "".concat(PREFIX, "-edit-top-bar-tabs")
      }, tabsInner)) : null, showCompactActions ? /*#__PURE__*/React.createElement("div", {
        className: classNames("".concat(PREFIX, "-edit-top-bar"), "".concat(PREFIX, "-edit-top-bar--compact"), "".concat(PREFIX, "-edit-top-bar--phone-actions-row")),
        role: "toolbar"
      }, /*#__PURE__*/React.createElement("div", {
        className: "".concat(PREFIX, "-edit-top-bar-actions")
      }, actionsInner)) : null, modalContextHolder);
    }
    return /*#__PURE__*/React.createElement("div", {
      className: classNames("".concat(PREFIX, "-edit-top-bar"), "".concat(PREFIX, "-read-canvas-tabs-bar"), "".concat(PREFIX, "-edit-top-bar--compact"), tabsHiddenClass, className),
      role: "toolbar",
      "aria-label": topBarLabels.aria
    }, !hideCanvasTabs ? /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "-edit-top-bar-tabs")
    }, tabsInner) : null, showCompactActions ? /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "-edit-top-bar-actions")
    }, actionsInner) : null, modalContextHolder);
  }
  if (hideCanvasTabs && !hasFullActions) {
    return null;
  }
  var fullTabsInner = /*#__PURE__*/React.createElement(CanvasTabs, {
    canvases: canvases,
    currentCanvasId: currentCanvasId,
    onTabChange: onTabChange,
    canEdit: canEditTabs,
    onAddCanvas: onAddCanvas,
    onRemoveCanvas: onRemoveCanvas,
    onRenameCanvas: onRenameCanvas,
    className: "".concat(PREFIX, "-edit-top-bar-canvas-tabs")
  });
  var fullActionsInner = /*#__PURE__*/React.createElement(React.Fragment, null, saveError ? /*#__PURE__*/React.createElement("span", {
    className: "".concat(PREFIX, "-edit-top-bar-error"),
    title: typeof saveError === 'string' ? saveError : saveError === null || saveError === void 0 ? void 0 : saveError.message
  }, typeof saveError === 'string' ? saveError : saveError === null || saveError === void 0 ? void 0 : saveError.message) : null, dirtyBadge, historyGroup, canvasTabsBarTrailing, extraActions, showExitGroup ? /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "-edit-top-bar-save-group")
  }, /*#__PURE__*/React.createElement("button", {
    type: "button",
    className: "".concat(PREFIX, "-edit-top-bar-btn"),
    disabled: saving,
    onClick: handleCancelClick
  }, topBarLabels.cancelEdit), /*#__PURE__*/React.createElement("button", {
    type: "button",
    className: classNames("".concat(PREFIX, "-edit-top-bar-btn"), 'primary'),
    disabled: saving,
    onClick: function onClick() {
      /**
       * 完成 = 保存 + 退出；保存按 onSave 同步触发，
       * 即便 onSave 是异步上报也立即调 onExitEdit，
       * 业务层若需「保存成功后再退出」可在自身 onExitEdit 内做控制。
       */
      onSave === null || onSave === void 0 || onSave();
      onExitEdit === null || onExitEdit === void 0 || onExitEdit();
    }
  }, saving ? topBarLabels.saving : topBarLabels.finishEdit)) : showSave ? /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "-edit-top-bar-save-group")
  }, /*#__PURE__*/React.createElement("button", {
    type: "button",
    className: classNames("".concat(PREFIX, "-edit-top-bar-btn"), 'primary'),
    disabled: saving,
    onClick: onSave
  }, saving ? topBarLabels.saving : topBarLabels.save)) : null);
  if (phoneLayout) {
    return /*#__PURE__*/React.createElement(React.Fragment, null, !hideCanvasTabs ? /*#__PURE__*/React.createElement("div", {
      className: classNames("".concat(PREFIX, "-edit-top-bar"), "".concat(PREFIX, "-read-canvas-tabs-bar"), "".concat(PREFIX, "-edit-top-bar--full-chrome"), "".concat(PREFIX, "-edit-top-bar--phone-edit-canvas-row"), className),
      role: "toolbar",
      "aria-label": topBarLabels.aria
    }, /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "-edit-top-bar-tabs")
    }, fullTabsInner)) : null, hasFullActions ? /*#__PURE__*/React.createElement("div", {
      className: classNames("".concat(PREFIX, "-edit-top-bar"), "".concat(PREFIX, "-edit-top-bar--full-chrome"), "".concat(PREFIX, "-edit-top-bar--phone-actions-row")),
      role: "toolbar"
    }, /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "-edit-top-bar-actions")
    }, fullActionsInner)) : null, modalContextHolder);
  }
  return /*#__PURE__*/React.createElement("div", {
    className: classNames("".concat(PREFIX, "-edit-top-bar"), "".concat(PREFIX, "-read-canvas-tabs-bar"), "".concat(PREFIX, "-edit-top-bar--full-chrome"), tabsHiddenClass, className),
    role: "toolbar",
    "aria-label": topBarLabels.aria
  }, !hideCanvasTabs ? /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "-edit-top-bar-tabs")
  }, fullTabsInner) : null, hasFullActions ? /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "-edit-top-bar-actions")
  }, fullActionsInner) : null, modalContextHolder);
}
export default FloorMapEditTopBar;