import type { CoverSprite } from "@ben-to/builder/domain";
import { publicAssetHref } from "./public-asset";

/**
 * Tuile d’une planche de sprites via `<img>` + décalage (plus fiable que `background-image` avec le runtime Solid).
 */
export const SpriteTile = (props: Readonly<{ sprite: CoverSprite; size?: number; class?: string }>) => {
  const size = () => props.size ?? 32;
  const scale = () => size() / props.sprite.cell;
  const imgW = () => Math.round(props.sprite.sheetWidth * scale());
  const imgH = () => Math.round(props.sprite.sheetHeight * scale());
  const offsetLeft = () => Math.round(-props.sprite.col * size());
  const offsetTop = () => Math.round(-props.sprite.row * size());
  return (
    <span
      class={props.class}
      aria-hidden="true"
      style={{
        display: "block",
        width: `${size()}px`,
        height: `${size()}px`,
        overflow: "hidden",
        position: "relative",
        "flex-shrink": "0"
      }}
    >
      <img
        src={publicAssetHref(props.sprite.sheet)}
        alt=""
        width={imgW()}
        height={imgH()}
        draggable={false}
        decoding="async"
        style={{
          position: "absolute",
          left: `${offsetLeft()}px`,
          top: `${offsetTop()}px`,
          "max-width": "none",
          width: `${imgW()}px`,
          height: `${imgH()}px`,
          "image-rendering": "pixelated"
        }}
      />
    </span>
  );
};
