<script>
  import { page } from '$app/stores';
  import axios from 'axios';
  import InfiniteLoading from '/src/lib/InfiniteLoading.svelte';
  import LoadingScreen from "/src/lib/LoadingScreen.svelte";
  import ErrorLoading from '/src/lib/ErrorLoading.svelte';

  let serverurl = 'https://recipesapi.computernetthings.ru';

  let recipes_list = [];
  let last_page = 1

  // First loading
  let recipes = axios.post(serverurl+"/recipes_by_category", {page:last_page, category:$page.params.category});
  recipes.then(function (response) {
      recipes_list = response.data.recipes;
  })
  .catch(function (error) {
      // handle error
      console.log(error);
  })

    // Inf loading
  function infiniteHandler({ detail: { loaded, complete } }) {
    last_page += 1;
    axios.post(serverurl+"/recipes_by_category", {page:last_page, category:$page.params.category}).then(
      function (response) {
        if (response.data.recipes != null) {
          recipes_list = [...recipes_list, ...response.data.recipes];
          loaded();
        } else {
          complete();
        }
      }
    )
  }
</script>

<div>
  <h5 class="text-center mt-14">Все рецепты в категории<br/>"{$page.params.category.toLowerCase()}"</h5>
    <div class="mx-auto max-w-2xl px-4 py-16 sm:px-6 lg:max-w-7xl lg:px-8">
        <h2 class="sr-only">Категории</h2>
        {#await recipes}
          <LoadingScreen/>
        {:then}
          {#if (recipes_list === null)}
            <ErrorLoading/>
          {:else}
            <div class="grid grid-cols-1 gap-x-6 gap-y-10 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 xl:gap-x-8">
              {#each recipes_list as recipe}
                <a href="/recipe/{recipe.id}" class="group transition duration-300 hover:scale-110">
                  <div class="aspect-h-1 aspect-w-1 w-full overflow-hidden rounded-lg bg-gray-200 xl:aspect-h-8 xl:aspect-w-7">
                    <img src="{serverurl}/recipe_img?filename={recipe.img}" alt="{recipe.title}" class="h-full w-full object-cover object-center transition duration-700 group-hover:opacity-90">
                  </div>
                  <h3 class="mt-3 text-base text-gray-700">{recipe.ctime} / {recipe.cal}</h3>
                  <p class="mt-0 text-lg font-medium text-gray-900">{recipe.title}</p>
                </a>
              {/each}
            </div>
            <InfiniteLoading on:infinite={infiniteHandler} />
          {/if}
        {:catch}
          <ErrorLoading/>
        {/await}
    </div>
</div>

<style>
  @font-face {
    font-family: 'AlegreyaSansSC';
    font-style: normal;
    font-weight: 800;
    src: url('/fonts/Alegreyasansscextrabold.ttf');
  }

  h5 {
        font-family: 'AlegreyaSansSC', sans-serif;
        font-size: 1.4em;
        margin-bottom: 1vh;
    }
</style>