import React from "react";
import { JSONTree } from "react-json-tree";
import { validateRicosDocument } from "./../../../ricos-schema/next-schema/index.js";
import { Button } from "../components/button.js";
import { jsonTreeTheme, mainTheme as theme } from "../theme.js";
const RichContentTree = ({ content, selectedNodeId }) => {
  const errors = React.useMemo(() => {
    const validationResult = validateRicosDocument(content);
    return validationResult.type === "ok" ? [] : validationResult.errors;
  }, [content]);
  const containerRef = React.useRef(null);
  const hasErrorUnder = isErrorUnderNode(errors);
  const getErrorFor = getErrorForNode(errors);
  const selectedTreePath = React.useMemo(() => {
    if (!selectedNodeId) {
      return void 0;
    }
    return findTreePathByNodeId(content, selectedNodeId);
  }, [content, selectedNodeId]);
  const isSelectedPath = React.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 = React.useCallback(
    (nodePath) => {
      if (!selectedTreePath) {
        return false;
      }
      const normalizedNodePath = [...nodePath].reverse();
      return normalizedNodePath.every(
        (pathSegment, index) => pathSegment === selectedTreePath[index]
      );
    },
    [selectedTreePath]
  );
  React.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__ */ React.createElement("div", { ref: containerRef }, /* @__PURE__ */ React.createElement("div", { style: { display: "flex", justifyContent: "flex-end" } }, errors.length ? /* @__PURE__ */ React.createElement(
    Button,
    {
      style: { border: "1px solid red", marginRight: "10px" },
      onClick: () => {
        console.log(errors);
      }
    },
    "Log Errors"
  ) : null, /* @__PURE__ */ React.createElement(
    Button,
    {
      onClick: () => {
        navigator.clipboard.writeText(JSON.stringify(content));
      },
      style: { marginRight: "10px" }
    },
    "Copy into clipboard"
  ), /* @__PURE__ */ React.createElement(
    Button,
    {
      onClick: () => {
        console.log(content);
      }
    },
    "Log to console"
  )), /* @__PURE__ */ React.createElement(
    JSONTree,
    {
      valueRenderer: (valueAsString, _value, ...nodePath) => {
        const error = getErrorFor(nodePath);
        if (error) {
          return /* @__PURE__ */ React.createElement("span", { style: getTreeNodeStyles(isSelectedPath(nodePath), { color: "red" }) }, valueAsString, " [Error: ", error.message, "]");
        }
        return /* @__PURE__ */ React.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__ */ React.createElement("span", { style: getTreeNodeStyles(isSelected) }, defaultView, " ", keysCount, " ", /* @__PURE__ */ React.createElement("span", { style: { color: "red" } }, error.message));
        }
        if (type === "Object" && value.type) {
          return /* @__PURE__ */ React.createElement("span", { style: getTreeNodeStyles(isSelected, hasError ? { color: "red" } : void 0) }, "{} ", value.type);
        }
        return /* @__PURE__ */ React.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__ */ React.createElement(
          "span",
          {
            "data-selected-tree-node": isSelected ? "true" : void 0,
            style: getTreeNodeStyles(isSelected)
          },
          label,
          ":"
        );
      },
      data: content,
      invertTheme: false,
      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: theme.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);
  });
};
export {
  RichContentTree
};
//# sourceMappingURL=rich-content-tree.js.map
