<script lang="ts">
  import LoadingSpinnerComponent from '$lib/components/LoadingSpinnerComponent.svelte';

  interface Props {
    moreAvailable?: boolean;
    isLoading?: boolean;
    loadOlderPosts: any;
  }

  let { moreAvailable = false, isLoading = false, loadOlderPosts }: Props = $props();
  let displayText = $derived.by(() => {
    if (isLoading) {
      return 'Loading...';
    } else if (!moreAvailable) {
      return 'You reached the end';
    }
    return 'Load More';
  });
  let title = $derived(moreAvailable ? 'Load More' : 'There be dragons!');
  let disabled: boolean = $derived(!moreAvailable || isLoading);

  /*const dispatch = createEventDispatcher<{
  loadOlderPosts: string;
}>();

function loadOlderPosts() {
  dispatch('loadOlderPosts');
}*/
</script>

<button onclick={() => loadOlderPosts()} {disabled} {title}>
  <div class="loading" class:collapsed={!isLoading}>
    <LoadingSpinnerComponent size="0.5em" thickness="6px" />
  </div>
  <span>{displayText}</span>
</button>

<style>
  button {
    padding: 0.75em;
    border-radius: 3px;
    border: none;
    background-color: var(--color-button);
    color: var(--color-button-text);
    cursor: grab;
    transition: all 0.3s ease-in-out;
    font-size: large;
    font-weight: bold;
    display: flex;
    align-items: center;
  }

  button:hover:not(:disabled) {
    background-color: var(--color-button-hover);
  }

  button:hover:not(:disabled):not(:active) {
    box-shadow: 6px 6px 5px 0 var(--color-button-shadow);
    translate: -2px -2px;
  }

  button:disabled {
    cursor: not-allowed;
    background-color: var(--color-button-deactivated);
  }

  button:not(:disabled) {
    box-shadow: 4px 4px 2px 0 var(--color-button-shadow);
  }

  .loading {
    margin-right: 3px;
    display: flex;
    overflow: hidden;
    max-width: 100%;
    transition: all 0.3s 0.5s;
  }

  /* Cannot be removed, so that it animates its width change */
  .collapsed {
    max-width: 0;
    margin-right: 0;
  }
</style>
