<script lang="ts">
  import { formatDate } from "../utils/time";
  import EveryMinute from "./EveryMinute.svelte";

  export let startTime: Date | string = new Date();
  export let endTime: Date | string = new Date();
  export let compact: boolean = false;

  let started = false;
  let overdue = false;
  let danger = false;
  let amount = 0;
  let amountStr = "0";
  let unit = "days";
  let titleTimeStr = "";
  let now = new Date();

  $: {
    overdue = false;
    unit = "days";

    const st = (startTime instanceof Date) ? startTime : new Date(startTime);
    const et = (endTime instanceof Date) ? endTime : new Date(endTime);

    if (now < st) {
      started = false;
      amount = (st.getTime() - now.getTime()) / 86400000
    } else {
      started = true;
      amount = (et.getTime() - now.getTime()) / 86400000
    }

    if (amount < 0) {
      overdue = true;
      amount = -amount;
    }

    danger = (!overdue && started && amount <= 3);
    
    if (amount < 2) {
      amount *= 24;
      unit = "hours"
    }
    if (amount < 2) {
      amount *= 60;
      unit = "minutes";
    }

    amount = Math.floor(amount);
    if (amount <= 1) {
      unit = unit.slice(0, -1);
    }

    if (amount < 1) {
      amountStr = "< 1"
    } else {
      amountStr = amount.toString()
    }

    if (compact) {
      unit = unit.slice(0, 1);
    }

    titleTimeStr = `${formatDate(new Date(startTime))} – ${formatDate(new Date(endTime))}`
  }
</script>

<EveryMinute bind:now={now} />
<span title={titleTimeStr}>
  {#if (overdue)}
    <span class="overdue">{amountStr}{compact ? "" : " "}{unit} {!compact ? "ago" : ""}</span>
  {:else if (started)}
    <span class:danger class="started">{amountStr}{compact ? "" : " "}{unit} {!compact ? "left" : ""}</span>
  {:else}
    <span class="pending">{compact ? "" : "In "}{amountStr}{compact ? "" : " "}{unit}</span>
  {/if}
</span>

<style>
  span {
    color: #ccc;
  }

  span.pending {
    color: #2797e2;
  }
  span.danger {
    color: #e28127;
  }
  span.overdue {
    color: #666666;
  }
</style>