import { useMemo, type CSSProperties } from "react";
import iconMap from "./data/2.0/iconMap.json";

type IconProps = {
  style?: CSSProperties;
  className?: string;
  iconName: string;
  size: number;
};
const iconCountPerSize = iconMap.reduce((acc, icon) => {
  acc.set(icon.size, (acc.get(icon.size) ?? 0) + 1);
  return acc;
}, new Map<number, number>());
const mapSizePerSize = new Map<number, number>();
for (let [size, count] of iconCountPerSize.entries()) {
  mapSizePerSize.set(size, Math.floor(Math.sqrt(count)) + 1);
}

function Icon({ style, className, iconName, size = 64 }: IconProps) {
  const icon = useMemo(() => iconMap.find((o) => o.name == iconName), [iconName]);
  const backgroundMap = `/data/2.0/icon_${icon?.size}.webp`;
  const bgsize = useMemo(() => {
    if (icon) return (mapSizePerSize.get(icon.size) ?? 1) * size;
    return size;
  }, [icon]);
  return (
    <i
      className={className}
      style={{
        ...style,
        backgroundImage: `url("${backgroundMap}")`,
        backgroundPositionX: (-(icon?.x ?? 0) * size) / (icon?.size ?? 1),
        backgroundPositionY: (-(icon?.y ?? 0) * size) / (icon?.size ?? 1),
        backgroundSize: `${bgsize}px`,
        height: size,
        width: size,
        display: "inline-block",
      }}
    ></i>
  );
}
export default Icon;
