<script>
 import { goto } from '$app/navigation';

 import { user } from '$lib/stores/user';
 import { getCategories } from '$lib/categories';
 import { getPromos } from '$lib/users';

 function showCategory(category) {
     goto(`categories/${category.id}`)
 }

 let filterPromo = "";
</script>

{#if $user && $user.is_admin}
    <a href="categories/new" class="btn btn-primary ml-1 float-end" title="Ajouter une catégorie">
        <i class="bi bi-plus"></i>
    </a>
    {#await getPromos() then promos}
        <div class="float-end me-2">
            <select class="form-select" bind:value={filterPromo}>
                <option value="">-</option>
                {#each promos as promo, pid (pid)}
                    <option value={promo}>{promo}</option>
                {/each}
            </select>
        </div>
    {/await}
{/if}
<h2>
  Catégories // cours
</h2>

{#await getCategories()}
    <div class="text-center">
        <div class="spinner-border text-danger mx-3" role="status"></div>
        <span>Chargement des catégories &hellip;</span>
    </div>
{:then categories}
    <table class="table table-sm table-striped table-hover">
        <thead>
            <tr>
                <th>ID</th>
                <th>Nom</th>
                <th>Promo</th>
                <th>Étendre</th>
            </tr>
        </thead>
        <tbody>
            {#each categories.filter((c) => (filterPromo === "" || filterPromo === c.promo)) as c (c.id)}
                <tr>
                    <td>{c.id}</td>
                    <td>
                        <a href="categories/{c.id}">{c.label}</a>
                    </td>
                    <td>{c.promo}</td>
                    <td>
                        <span
                            class="badge"
                            class:bg-success={c.expand}
                            class:bg-danger={!c.expand}
                        >
                            {c.expand?"Oui":"Non"}
                        </span>
                    </td>
                </tr>
            {/each}
        </tbody>
    </table>
{/await}
