<script lang="ts">
    import Pager from '$lib/components/Pager.svelte';
    import type { ActiveJob } from '$lib/api/admin';
    import SearchBar from './SearchBar.svelte';

    let {
        jobs,
        total,
        page,
        totalPages,
        search = $bindable(''),
        onSearch,
        onPageChange
    }: {
        jobs: ActiveJob[];
        total: number;
        page: number;
        totalPages: number;
        search?: string;
        onSearch: () => void;
        onPageChange: (p: number) => void;
    } = $props();
</script>

<section class="backlog">
    <div class="deadhead">
        <h2>Queued chapters ({total})</h2>
        <div class="deadtools">
            <SearchBar bind:value={search} {onSearch} />
        </div>
    </div>
    {#if jobs.length === 0}
        <p class="muted">No chapters queued.</p>
    {:else}
        <table class="dead">
            <thead>
                <tr>
                    <th>Manga / Chapter</th>
                    <th>State</th>
                    <th>Att.</th>
                </tr>
            </thead>
            <tbody>
                {#each jobs as j (j.id)}
                    <tr>
                        <td>
                            {j.manga_title ?? '(unknown)'}
                            {#if j.chapter_number != null}· ch.{j.chapter_number}{/if}
                        </td>
                        <td>
                            <span
                                class={`badge ${j.state === 'running' ? 'badge-downloading' : 'badge-not_downloaded'}`}
                                >{j.state}</span
                            >
                        </td>
                        <td>{j.attempts}/{j.max_attempts}</td>
                    </tr>
                {/each}
            </tbody>
        </table>
        <Pager {page} {totalPages} onChange={onPageChange} />
    {/if}
</section>

<style>
    h2 {
        margin: 0 0 var(--space-3) 0;
        font-size: var(--font-sm);
        color: var(--text-muted);
        text-transform: uppercase;
        letter-spacing: 0.04em;
    }
    table {
        width: 100%;
        border-collapse: collapse;
    }
    th,
    td {
        padding: var(--space-2);
        text-align: left;
        border-bottom: 1px solid var(--border);
        font-size: var(--font-sm);
    }
    .deadhead {
        display: flex;
        justify-content: space-between;
        align-items: center;
        gap: var(--space-3);
        flex-wrap: wrap;
    }
    .deadtools {
        display: flex;
        gap: var(--space-2);
    }
    .muted {
        color: var(--text-muted);
    }
    .backlog {
        margin-top: var(--space-4);
    }
</style>
