import type { ToolType } from "../store/editorStore.types";
import { clampPositionToStage, fitSizeToStage } from "./stageBounds";

const STICKER_MAX_SIZE = 120;

export const scaleStickerDimensions = (
  naturalWidth: number,
  naturalHeight: number,
  maxSize = STICKER_MAX_SIZE,
) => {
  let width = naturalWidth;
  let height = naturalHeight;

  if (width > maxSize || height > maxSize) {
    const ratio = Math.min(maxSize / width, maxSize / height);
    width = Math.round(width * ratio);
    height = Math.round(height * ratio);
  }

  return { width, height };
};

export const createStickerObject = (
  imageUrl: string,
  centerX: number,
  centerY: number,
  width: number,
  height: number,
  stageWidth?: number,
  stageHeight?: number,
) => {
  let w = width;
  let h = height;
  if (stageWidth && stageHeight) {
    ({ width: w, height: h } = fitSizeToStage(w, h, stageWidth, stageHeight));
  }
  let x = Math.round(centerX - w / 2);
  let y = Math.round(centerY - h / 2);
  if (stageWidth && stageHeight) {
    ({ x, y } = clampPositionToStage(x, y, w, h, stageWidth, stageHeight));
  }
  return {
    id: `sticker-${Date.now()}`,
    type: "sticker" as ToolType,
    x,
    y,
    width: w,
    height: h,
    imageUrl,
  };
};
