<script lang="ts">
    import { loadRepos, repos } from '$lib/stores';
    import { timeSince, checkImage, IMAGE_URL_SUFFIX } from '$lib/api/git';
    import { toasts } from 'svelte-toasts';

    import { GridGallery, Card, Loading, Section, Collapsible } from '@luke-else/component-lib';

    let repoImages: Record<string, string | null> = {};

    // When repos load, check for images
    $: if ($repos.length) {
        (async () => {
            for (const repo of $repos) {
                if (repoImages[repo.name] === undefined) {
                    const url = repo.html_url + IMAGE_URL_SUFFIX;
                    repoImages[repo.name] = (await checkImage(repo)) ? url : null;
                }
            }
        })();
    }
</script>
<Section label="[Repositories]">
    {#await loadRepos()}
        <Loading />
    {:then _}
        {#if $repos.length == 0}
            {console.log('No Repos')}
            <div style="display: none;">
                {toasts.add({
                    title: 'Error',
                    description: 'Failed to load repositories',
                    duration: 5000,
                    type: 'error',
                    placement: 'bottom-center',
                    showProgress: true
                })}
            </div>
            <p>Sorry... we can't show you anything here</p>
        {/if}
        <!-- Repositories loaded successfully -->
        <GridGallery>
            {#each $repos as repo}
                <!-- <Loading /> -->
                <Card
                    containerStyle="opacity-100 hover:opacity-100 hover:scale-[105%] md:opacity-70 transition-all duration-300"
                >
                    <h2 slot="headerLeft">{repo.name}</h2>
                    <h2 slot="headerRight" class="text-sm text-gray-500">
                        {repo.language}
                    </h2>
                    <div class="flex flex-col gap-5" slot="content">
                        {repo.description}
                        {#if repoImages[repo.name]}
                            <Collapsible>
                                <span slot="label" class="text-lg">See More</span>
                                <!-- svelte-ignore a11y_img_redundant_alt -->
                                <img
                                    slot="content"
                                    src={repoImages[repo.name]}
                                    alt="repo image"
                                    class=""
                                />
                            </Collapsible>
                        {/if}
                    </div>
                    <h3 slot="footerLeft">
                        Last Updated: {timeSince(repo.updated_at)}
                    </h3>
                </Card>
            {/each}
        </GridGallery>
    {/await}
</Section>
