"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var rich_content_tree_exports = {};
__export(rich_content_tree_exports, {
  RichContentTree: () => RichContentTree
});
module.exports = __toCommonJS(rich_content_tree_exports);
var import_react = __toESM(require("react"));
var import_react_json_tree = require("react-json-tree");
var import_next_schema = require("./../../../ricos-schema/next-schema/index.js");
var import_button = require("../components/button.js");
var import_theme = require("../theme.js");
const RichContentTree = ({ content, selectedNodeId }) => {
  const errors = import_react.default.useMemo(() => {
    const validationResult = (0, import_next_schema.validateRicosDocument)(content);
    return validationResult.type === "ok" ? [] : validationResult.errors;
  }, [content]);
  const containerRef = import_react.default.useRef(null);
  const hasErrorUnder = isErrorUnderNode(errors);
  const getErrorFor = getErrorForNode(errors);
  const selectedTreePath = import_react.default.useMemo(() => {
    if (!selectedNodeId) {
      return void 0;
    }
    return findTreePathByNodeId(content, selectedNodeId);
  }, [content, selectedNodeId]);
  const isSelectedPath = import_react.default.useCallback(
    (nodePath) => {
      if (!selectedTreePath) {
        return false;
      }
      const normalizedNodePath = [...nodePath].reverse();
      return normalizedNodePath.length === selectedTreePath.length && normalizedNodePath.every((pathSegment, index) => pathSegment === selectedTreePath[index]);
    },
    [selectedTreePath]
  );
  const isSelectionUnderNode = import_react.default.useCallback(
    (nodePath) => {
      if (!selectedTreePath) {
        return false;
      }
      const normalizedNodePath = [...nodePath].reverse();
      return normalizedNodePath.every(
        (pathSegment, index) => pathSegment === selectedTreePath[index]
      );
    },
    [selectedTreePath]
  );
  import_react.default.useEffect(() => {
    if (!selectedNodeId || !containerRef.current) {
      return;
    }
    const frameId = window.requestAnimationFrame(() => {
      containerRef.current?.querySelector('[data-selected-tree-node="true"]')?.scrollIntoView({
        block: "center"
      });
    });
    return () => {
      window.cancelAnimationFrame(frameId);
    };
  }, [selectedNodeId, selectedTreePath]);
  return /* @__PURE__ */ import_react.default.createElement("div", { ref: containerRef }, /* @__PURE__ */ import_react.default.createElement("div", { style: { display: "flex", justifyContent: "flex-end" } }, errors.length ? /* @__PURE__ */ import_react.default.createElement(
    import_button.Button,
    {
      style: { border: "1px solid red", marginRight: "10px" },
      onClick: () => {
        console.log(errors);
      }
    },
    "Log Errors"
  ) : null, /* @__PURE__ */ import_react.default.createElement(
    import_button.Button,
    {
      onClick: () => {
        navigator.clipboard.writeText(JSON.stringify(content));
      },
      style: { marginRight: "10px" }
    },
    "Copy into clipboard"
  ), /* @__PURE__ */ import_react.default.createElement(
    import_button.Button,
    {
      onClick: () => {
        console.log(content);
      }
    },
    "Log to console"
  )), /* @__PURE__ */ import_react.default.createElement(
    import_react_json_tree.JSONTree,
    {
      valueRenderer: (valueAsString, _value, ...nodePath) => {
        const error = getErrorFor(nodePath);
        if (error) {
          return /* @__PURE__ */ import_react.default.createElement("span", { style: getTreeNodeStyles(isSelectedPath(nodePath), { color: "red" }) }, valueAsString, " [Error: ", error.message, "]");
        }
        return /* @__PURE__ */ import_react.default.createElement("span", { style: getTreeNodeStyles(isSelectedPath(nodePath)) }, valueAsString);
      },
      getItemString: (type, value, defaultView, keysCount, nodePath) => {
        const error = getErrorFor(nodePath);
        const hasError = hasErrorUnder(nodePath);
        const isSelected = isSelectedPath(nodePath);
        if (error) {
          return /* @__PURE__ */ import_react.default.createElement("span", { style: getTreeNodeStyles(isSelected) }, defaultView, " ", keysCount, " ", /* @__PURE__ */ import_react.default.createElement("span", { style: { color: "red" } }, error.message));
        }
        if (type === "Object" && value.type) {
          return /* @__PURE__ */ import_react.default.createElement("span", { style: getTreeNodeStyles(isSelected, hasError ? { color: "red" } : void 0) }, "{} ", value.type);
        }
        return /* @__PURE__ */ import_react.default.createElement("span", { style: getTreeNodeStyles(isSelected, hasError ? { color: "red" } : void 0) }, defaultView, " ", keysCount);
      },
      labelRenderer: (nodePath, _nodeType, _expanded, _expandable) => {
        const [label] = nodePath;
        const isSelected = isSelectedPath(nodePath);
        return /* @__PURE__ */ import_react.default.createElement(
          "span",
          {
            "data-selected-tree-node": isSelected ? "true" : void 0,
            style: getTreeNodeStyles(isSelected)
          },
          label,
          ":"
        );
      },
      data: content,
      invertTheme: false,
      theme: import_theme.jsonTreeTheme,
      hideRoot: true,
      shouldExpandNode: (nodePath) => hasErrorUnder(nodePath) || isSelectionUnderNode(nodePath)
    }
  ));
};
const getTreeNodeStyles = (isSelected, style) => {
  if (!isSelected) {
    return style;
  }
  return {
    ...style,
    background: "rgba(137, 220, 235, .18)",
    color: import_theme.mainTheme.white,
    borderRadius: "3px",
    padding: "1px 4px"
  };
};
const getErrorForNode = (errors) => (nodePath) => {
  if (!errors.length) {
    return;
  }
  const nodePathAsPointer = [...nodePath].reverse().map((p) => p.toString());
  return errors.find(({ instancePath }) => {
    return instancePath.length === nodePathAsPointer.length && instancePath.every((p, i) => p === nodePathAsPointer[i]);
  });
};
const findTreePathByNodeId = (value, selectedNodeId, currentPath = []) => {
  if (!value || typeof value !== "object") {
    return void 0;
  }
  const objectValue = value;
  if (!Array.isArray(value) && typeof objectValue.id === "string" && objectValue.id === selectedNodeId && typeof objectValue.type === "string") {
    return currentPath;
  }
  if (Array.isArray(value)) {
    for (const [index, child] of value.entries()) {
      const nestedPath = findTreePathByNodeId(child, selectedNodeId, [...currentPath, index]);
      if (nestedPath) {
        return nestedPath;
      }
    }
    return void 0;
  }
  for (const [key, child] of Object.entries(value)) {
    const nestedPath = findTreePathByNodeId(child, selectedNodeId, [...currentPath, key]);
    if (nestedPath) {
      return nestedPath;
    }
  }
  return void 0;
};
const isErrorUnderNode = (errors) => (nodePath) => {
  if (!errors.length) {
    return false;
  }
  const nodePathAsPointer = [...nodePath].reverse().map((p) => p.toString());
  return !!errors.find(({ instancePath }) => {
    return nodePathAsPointer.every((p, i) => instancePath[i] === p);
  });
};
//# sourceMappingURL=rich-content-tree.js.map
