<script>
  import { createEventDispatcher, onDestroy } from 'svelte';

  export let starts_on = false;

  let time_remaining = starts_on ? starts_on.getTime() - Date.now() : 0;
  let days = 0;
  let hours = 0;
  let minutes = 0;
  let seconds = 0;

  const dispatch = createEventDispatcher();

  const display_delta = () => {
    days = Math.floor(time_remaining / (1000 * 60 * 60 * 24));
    hours = Math.floor((time_remaining % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    minutes = Math.floor((time_remaining % (1000 * 60 * 60)) / (1000 * 60));
    seconds = Math.floor((time_remaining % (1000 * 60)) / 1000);
  }

  const pad = (number) => number.toString().padStart(2, '0');

  const timer = setInterval(() => {
    time_remaining = starts_on.getTime() - Date.now();

    if(time_remaining > 0) {
      display_delta();
    } else {
      clearInterval(timer);
      dispatch("done");
    }
  }, 1000);

  display_delta();

  onDestroy(() => clearInterval(timer));
</script>

<style>
  countdown {
    display: flex;
    justify-content: center;
    flex-direction: column;
  }

  countdown h1,
  countdown h2 {
    color: var(--color-bg-secondary);
    font-size: 7vw;
    margin-top: 0;
    margin-bottom: 0;
    text-shadow: 8px 8px 5px var(--color-overlay-shadow);
  }

  countdown h2 {
    font-size: 5vw;
  }
</style>


<countdown>

{#if days > 0 || hours > 8}
  <h1>Streaming On</h1>
  <h2>{ new Intl.DateTimeFormat('en', { month: 'short', day: '2-digit'}).format(starts_on) }</h2>
  <h2>@ {  new Intl.DateTimeFormat('en', { hour: 'numeric', minute: '2-digit', hour12: true, timeZoneName: 'short'}).format(starts_on) } </h2>
{:else if hours > 0}
  <h1>Streaming At</h1>
  <h1>{  new Intl.DateTimeFormat('en', { hour: 'numeric', minute: '2-digit', hour12: true}).format(starts_on) } Today</h1>
{:else if minutes > 1}
  <h1>Starting In</h1>
  <h1>{ minutes } minutes</h1>
{:else if minutes == 1}
  <h1>Starting In</h1>
  <h1>{ pad(minutes) }:{ pad(seconds) } minute</h1>
{:else if seconds > 0}
  <h1>Starting In</h1>
  <h1>{ pad(seconds) } seconds</h1>
{:else}
  <h1>Starting Soon</h1>
{/if}
</countdown>
