// konva-utils.js
export function attachStageResizer(root, stage) {
  const observer = new ResizeObserver(() => {
    if (!stage) return;

    stage.width(root.clientWidth);
    stage.height(root.clientHeight);
    stage.batchDraw();
  });

  observer.observe(root);
  return observer;
}

// масштабирует картинку по stage
export function fitImageToStage(konvaImage, stage) {
  const img = konvaImage.image();
  const sw = stage.width();
  const sh = stage.height();
  const iw = img.naturalWidth;
  const ih = img.naturalHeight;
  const scale = Math.min(sw / iw, sh / ih);

  konvaImage.width(iw);
  konvaImage.height(ih);
  konvaImage.scale({ x: scale, y: scale });

  // центрируем
  konvaImage.x((sw - iw * scale) / 2);
  konvaImage.y((sh - ih * scale) / 2);
}

export function coverImageToStage(konvaImage, stage) {
  const img = konvaImage.image();
  const sw = stage.width();
  const sh = stage.height();
  const iw = img.naturalWidth;
  const ih = img.naturalHeight;
  const scale = Math.max(sw / iw, sh / ih);

  konvaImage.width(iw);
  konvaImage.height(ih);
  konvaImage.scale({ x: scale, y: scale });

  // центрируем и обрезаем по центру
  konvaImage.x((sw - iw * scale) / 2);
  konvaImage.y((sh - ih * scale) / 2);
}
