<script>
  import rando from 'randomcolor';
  import { visibility } from "$/client/helpers.js";

  export let width = 800;
  export let height = 450;
  // if you don't set any colors then it will use randomColor with these options
  export let random_options = {hue: "monochrome", "format": "rgbArray", "luminosity": "random", count: 10};
  // default colors are simple grays taken from a still image
  export let colors = rando(random_options);
  export let src = "";
  export let lazy = false;
  let show_image = false;
  let img_id = `image-${Math.floor(Math.random() * 1000000)}`;
  let in_view = false;

  const visible = () => in_view = true;

  const image_loaded = () => show_image = true;

</script>

<style>
  img {
    z-index: -1;
    opacity: 0.5;
  }

  img.visible {
    opacity: 1;
    transition: opacity 0.5s;
  }

  svg {
    z-index: 1;
    opacity: 1;
  }

  svg.hidden {
    opacity: 0.5;
    transition: opacity 0.5s;
    z-index: -1;
  }
</style>

<cover class="stacked" use:visibility on:visible={ visible }>

  <svg class="layer" class:hidden={ show_image && in_view } xmlns="http://www.w3.org/2000/svg" version="1.1" viewbox="0 0 {width} {height}">
    <filter id="blur" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
      <feGaussianBlur stdDeviation="40 40" edgeMode="duplicate" />
      <feComponentTransfer>
      <feFuncA type="discrete" tableValues="1 1" />
      </feComponentTransfer>
    </filter>
    <g filter="url(#blur)">
    {#each colors as row,i}
      {#each colors as color,j}
        <rect x="{ i * width / colors.length }" y="{ j * height / colors.length}" width="{ width / colors.length}" height="{ height / colors.length}" stroke="none" fill="rgb({ colors[Math.floor(Math.random() * colors.length)] })" fill-opacity="1" stroke-opacity="0.8" />
      {/each}
    {/each}
    </g>
  </svg>

  {#if in_view}
    <img class="layer" class:visible={ show_image } src={src} id={ img_id } loading={ lazy ? 'lazy' : 'eager'} on:load={ image_loaded }>
  {/if}
</cover>
