import { useLayoutEffect, type CSSProperties } from "react";
import type Konva from "konva";
import KonvaLib from "konva";

export function getKonvaBlurProps(blur?: number) {
  const blurRadius = blur ?? 0;
  if (blurRadius <= 0) return {};
  return {
    filters: [KonvaLib.Filters.Blur],
    blurRadius,
  };
}

export function getCssBlurStyle(blur?: number, scale = 1): CSSProperties {
  const blurPx = blur ?? 0;
  if (blurPx <= 0) return {};
  return { filter: `blur(${blurPx * scale}px)` };
}

export function useShapeBlurCache(
  shapeRef: React.RefObject<Konva.Shape | null>,
  blur: number | undefined,
  cacheKey: unknown,
) {
  useLayoutEffect(() => {
    const node = shapeRef.current;
    if (!node) return;

    const blurRadius = blur ?? 0;
    if (blurRadius > 0) {
      node.clearCache();
      node.cache({
        offset: blurRadius,
        drawBorder: false,
      });
    } else {
      node.clearCache();
    }

    node.getLayer()?.batchDraw();
  }, [blur, cacheKey, shapeRef]);
}
