<script>
  import { Icon } from 'sveltestrap';

  export let state;
  export let value;
  export let collapsed = undefined;
  export let url;

  import { UNCHECKED, CHECKED, WEIRD } from './stores';
  import { createEventDispatcher } from 'svelte';

  const icons = new Map()
    .set(UNCHECKED, 'square')
    .set(CHECKED, 'check-square-fill')
    .set(WEIRD, 'square-half');

  const dispatch = createEventDispatcher();

  const handleClick = () => {
    state = state === CHECKED ? UNCHECKED : CHECKED;
    dispatch('change', { value: state });
  };

  $: icon = icons.get(state);

  $: chevron = collapsed ? 'chevron-expand' : 'chevron-contract';
</script>

<span class="cal w-100 d-block" on:click={handleClick}>
  <Icon name={icon} class="ms-2" />
  <span class="ms-1 d-inline-block cal-title">{value}</span>
  <span class="float-end">
    {#if url}
      <a href={url} class="cal-link" download={value} on:click|stopPropagation>
        <Icon name="cloud-download" />
      </a>
    {/if}

    {#if collapsed !== undefined}
      <span class="cal-link" on:click|stopPropagation={() => (collapsed = !collapsed)}>
        <Icon name={chevron} />
      </span>
    {/if}
  </span>
</span>

<style>
  .cal-link {
    margin-right: 0.5rem;
    padding: 3px;
    color: inherit;
  }
  .cal-link:hover {
    color: #aabbfe;
    text-shadow: 2px 2px 3px #62a1fe;
  }
  .cal-title {
    max-width: 75%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: bottom;
  }

  .cal {
    cursor: pointer;
    padding: 0.2em;
    border-radius: 4px;
  }

  .cal:hover {
    background-color: #6c757d;
    color: #fff;
  }
</style>
