<script lang="ts">
  import { onMount } from "svelte";
  import createFishes from "./fishes/webgl-fishes";
  import { Color } from "ogl";
  import { colors, rgbToHex } from "@helpers/colors";

  let canvasBottom: HTMLCanvasElement;

  let speed = 0;
  let timeOffset = Math.random() * 100000;

  let fishCanvasBack: ReturnType<typeof createFishes>;
  let render = true;

  const color = new Color("#ffffff");

  function updateColor(c: string) {
    const d = new Color(rgbToHex(c));
    color.set(d.r, d.g, d.b);
    fishCanvasBack?.resize();
  }

  $: if ($colors.background) {
    updateColor($colors.background);
  }

  const handleResize = () => {
    fishCanvasBack.resize();
    render = window.innerWidth > 500;
  };

  let loaded = false;

  onMount(async () => {
    fishCanvasBack = createFishes(canvasBottom, { amount: 100, color });

    fishCanvasBack.resize();

    requestAnimationFrame(update);
    function update(t) {
      requestAnimationFrame(update);
      speed *= 0.99;
      render && fishCanvasBack.update(t, timeOffset);
    }
    loaded = true;
  });
</script>

<svelte:window
  on:resize={handleResize}
  on:scroll={() => {
    speed = Math.min(speed + 0.001, 0.15);
    timeOffset += speed;
  }} />

<canvas id="bottom" bind:this={canvasBottom} class:loaded />

<!-- <canvas id="top" bind:this={canvasTop} /> -->
<style>
  canvas {
    width: 100% !important;
    height: unset !important;
    position: fixed;
    top: 0px;
    left: 0px;
    z-index: -1;
    opacity: 0;
    transition: opacity 4s;
  }

  canvas.loaded {
    opacity: 0.8;
  }
</style>
