"use client";
import { jsx } from "../../packages/jsx/src/jsx-runtime.js";
import { constants } from "ethers";
import md5 from "md5";
import { useRef, useEffect } from "react";
import { BorderRadius } from "../../tokens/BorderRadius.js";
const Identicon = ({ account, size, padding = 0, ...props }) => {
  const canvasEl = useRef(null);
  useEffect(() => {
    if (!canvasEl.current) {
      return;
    }
    const count = 5;
    const hash = md5(account ? account.toLowerCase() : constants.AddressZero);
    const block = Math.floor((size ?? 1e3) / count);
    const hashcolor = hash.slice(0, 6);
    const pad = padding;
    canvasEl.current.width = block * count + pad;
    canvasEl.current.height = block * count + pad;
    const arr = hash.split("").map((el) => {
      const _el = parseInt(el, 16);
      if (_el < 8) {
        return 0;
      } else {
        return 1;
      }
    });
    const map = [];
    map[0] = map[4] = arr.slice(0, 5);
    map[1] = map[3] = arr.slice(5, 10);
    map[2] = arr.slice(10, 15);
    const ctx = canvasEl.current.getContext("2d");
    if (!ctx) {
      return;
    }
    ctx.imageSmoothingEnabled = false;
    ctx.clearRect(0, 0, canvasEl.current.width, canvasEl.current.height);
    map.forEach((row, i) => {
      row.forEach((el, j) => {
        if (el) {
          ctx.fillStyle = "#" + hashcolor;
          ctx.fillRect(block * i + pad, block * j + pad, block - pad, block - pad);
        } else {
          ctx.fillStyle = "white";
          ctx.fillRect(block * i + pad, block * j + pad, block - pad, block - pad);
        }
      });
    });
  }, [canvasEl, account, size, padding]);
  return /* @__PURE__ */ jsx(
    "div",
    {
      "data-testid": "identicon",
      sx: {
        width: size,
        aspectRatio: "1"
      },
      ...props,
      children: /* @__PURE__ */ jsx(
        "canvas",
        {
          ref: canvasEl,
          style: {
            width: "100%",
            height: "100%",
            borderRadius: BorderRadius.FULL,
            overflow: "hidden"
          }
        }
      )
    }
  );
};
export {
  Identicon
};
