import Konva from "konva";
import type { EditorObject } from "../store/editorStore";

/** Resolve editor object from a Konva node id (supports masked-* groups). */
export const resolveObjectFromNodeId = (
  nodeId: string,
  objects: EditorObject[],
): EditorObject | undefined => {
  if (nodeId.startsWith("masked-")) {
    const objectId = nodeId.slice("masked-".length);
    return objects.find((obj) => obj.id === objectId);
  }
  return objects.find((obj) => obj.id === nodeId);
};

/**
 * Base width/height used for transform baking.
 * For images, Konva may use natural image size while store width is still unset.
 */
export const getNodeTransformDimensions = (
  node: Konva.Node,
): { width: number; height: number } => {
  const nodeWidth = node.width();
  const nodeHeight = node.height();
  if (nodeWidth > 0 && nodeHeight > 0) {
    return { width: nodeWidth, height: nodeHeight };
  }

  const imageNode =
    "findOne" in node
      ? (node as Konva.Container).findOne<Konva.Image>("Image")
      : undefined;
  if (imageNode && imageNode.width() > 0 && imageNode.height() > 0) {
    return { width: imageNode.width(), height: imageNode.height() };
  }

  const rect = node.getClientRect({ skipTransform: true });
  if (rect.width > 0 && rect.height > 0) {
    return { width: rect.width, height: rect.height };
  }

  return { width: 100, height: 100 };
};

export const nodeHasPendingTransform = (node: Konva.Node): boolean =>
  Math.abs(node.scaleX() - 1) > 0.0001 ||
  Math.abs(node.scaleY() - 1) > 0.0001;
