// ── Avatar ────────────────────────────────────────────────────────────────────
// Deterministic patterned avatar derived from username.
// Two hues + one repeating shape (circle / square / diamond) tiled in a grid.

function Avatar({ username, size = 28 }) {
  const instanceId = React.useId().replace(/[^a-z0-9]/gi, "");

  function strHash(str, seed) {
    let h = (seed | 0) ^ 0x811c9dc5;
    for (let i = 0; i < str.length; i++) {
      h ^= str.charCodeAt(i);
      h = Math.imul(h, 0x01000193) >>> 0;
    }
    return h;
  }

  const h1 = strHash(username, 0);
  const h2 = strHash(username, 17);
  const h3 = strHash(username, 37);

  const hue1 = h1 % 360;
  // Offset second hue by 100–160° for contrast
  const hue2 = (hue1 + 100 + (h2 % 60)) % 360;

  const bg = `hsl(${hue1}, 55%, 40%)`;
  const fg = `hsl(${hue2}, 65%, 78%)`;

  const shapes = ["circle", "square", "diamond"];
  const shape = shapes[h3 % 3];

  const tile = size / 4;
  const m = tile / 2; // tile center
  const r = tile * 0.3; // shape radius / half-size

  let shapeEl;
  if (shape === "circle") {
    shapeEl = <circle cx={m} cy={m} r={r} fill={fg} />;
  } else if (shape === "square") {
    shapeEl = (
      <rect x={m - r} y={m - r} width={r * 2} height={r * 2} fill={fg} />
    );
  } else {
    shapeEl = (
      <polygon
        points={`${m},${m - r} ${m + r},${m} ${m},${m + r} ${m - r},${m}`}
        fill={fg}
      />
    );
  }

  const uid = `av${h1.toString(36)}${instanceId}`;

  return (
    <svg
      width={size}
      height={size}
      viewBox={`0 0 ${size} ${size}`}
      style={{ display: "block", flexShrink: 0 }}
    >
      <defs>
        <pattern
          id={uid}
          x="0"
          y="0"
          width={tile}
          height={tile}
          patternUnits="userSpaceOnUse"
        >
          <rect width={tile} height={tile} fill={bg} />
          {shapeEl}
        </pattern>
        <clipPath id={`c${uid}`}>
          <circle cx={size / 2} cy={size / 2} r={size / 2} />
        </clipPath>
      </defs>
      <rect
        width={size}
        height={size}
        fill={`url(#${uid})`}
        clipPath={`url(#c${uid})`}
      />
    </svg>
  );
}
