<script lang="ts">
  import { onMount } from "svelte";

  const BADGE_HEIGHT = 3;
  export let address: string;

  let canvas: HTMLCanvasElement | undefined;
  let width = 0;

  const bytes = [...address].map((c) => c.charCodeAt(0));
  while (bytes.length % (3 * BADGE_HEIGHT) !== 0) {
    bytes.push(bytes[bytes.length - 1]);
  }

  width = Math.ceil(bytes.length / 3 / BADGE_HEIGHT);

  onMount(() => {
    const ctx = canvas?.getContext("2d");
    if (!ctx) {
      console.warn("Couldn't initialize canvas!");
      return;
    }

    const hueRange = 120;
    const hueCenter = 90 + bytes.length * 2.5;

    let idx = 0;
    function draw() {
      const tmp = [];
      while (bytes.length > 0 && tmp.length < 3) {
        tmp.push(bytes.shift());
      }
      while (tmp.length < 3) {
        tmp.push(tmp[tmp.length - 1]);
      }

      const h = (tmp[0] / 128) * hueRange + hueCenter - hueRange / 2;
      const s = (tmp[1] / 128) * 100;
      const l = (tmp[2] / 128) * 100;
      ctx.fillStyle = `hsl(${h},${s}%,${l}%)`;
      ctx.fillRect(Math.floor(idx / BADGE_HEIGHT), idx % BADGE_HEIGHT, 1, 1);
      idx++;
      if (bytes.length > 0) {
        requestAnimationFrame(draw);
      }
    }

    requestAnimationFrame(draw);
  });
</script>

<canvas bind:this={canvas} {width} height="3" title={address} />

<style scoped>
  canvas {
    display: inline-block;
    height: 1em;
    image-rendering: optimizeSpeed;
  }
</style>
