<script>
  import { onMount } from "svelte";

  export let value;
  export let goal;

  let smoothValue = value;
  let bars = [];
  let timeout = null;

  function update(value, goal) {
    const bars = [];
    let gold = (goal / 1000);
    let red = gold + 3;
    
    for (let i = 0;; ++i) {
      let v = value - (i * 1000);
      if (v > 1000) {
        v = 1000;
      } else if (v < 0) {
        v = 0;
      }

      if (i >= red && v === 0) {
        break;
      }

      bars.push({
        green: i < gold,
        gold: i >= gold && i < red,
        red: i >= red,
        value: v,
        full: v === 1000,
      })
    }

    return bars;
  }

  onMount(() => {
    return () => clearTimeout(timeout);
  })

  $: bars = update(smoothValue, goal);

  $: if (smoothValue !== value && timeout === null) {
    timeout = setInterval(() => {
      if (smoothValue < value) {
        smoothValue += 100;
        if (smoothValue > value) {
          smoothValue = value;
        }
      } else if (smoothValue > value) {
        smoothValue -= 100;
        if (smoothValue < value) {
          smoothValue = value;
        }
      } else {
        clearTimeout(timeout);
        timeout = null;
      }
    }, 1000/30);
  }
</script>

{#each bars as bar}
  <div class="bar" class:red={bar.red} class:green={bar.green} class:gold={bar.gold} class:full={bar.full}>
    <div class="content" style={`height: ${bar.value / 10}%; top: ${(1000 - bar.value) / 10}%`}>
    </div>
  </div>
{/each}

<style>
  div.bar {
    display: inline-block;
    background: #111;
    width: 1.5ch;
    height: 1em;
    margin-right: 0.5ch;
  }

  div.bar > div.content {
    width: 100%;
    position: relative;
  }

  div.bar.green {
    border: 0.1px solid #4da069;
  }
  div.bar.green > div.content {
    background-color: #4da069;
  }
  div.bar.green.full > div.content {
    background-color: #45fc82;
    box-shadow: 0px 0px 2px #45fc82;
  }
  div.bar.gold {
    border: 0.1px solid #9b7a1f;
  }
  div.bar.gold > div.content {
    background-color: #9b7a1f;
  }
  div.bar.gold.full > div.content {
    background-color: #ffc936;
    box-shadow: 0px 0px 2px #ffc936;
  }
  div.bar.red {
    border: 0.1px solid #880000;
  }
  div.bar.red > div.content {
    background-color: #880000;
  }
  div.bar.red.full > div.content {
    background-color: #bb0000;
    box-shadow: 0px 0px 2px #ff0000;
  }
</style>