<script>
    import {onMount}         from 'svelte';
    import { useTinyRouter } from 'svelte-tiny-router';

    import { api }           from '../../urls.svelte.js';
    import { error, yikes }  from '../../warn.svelte';
    import { t }             from '../../translations.svelte.js';

    import Reference         from './Reference.svelte';

    let { tag } = $props();
    let router  = useTinyRouter();
    let uses    = $state(null);

    function headline(module){
        if (module == 'stock') return t(module);
        if (module.endsWith('s')) return t(`${module}s`);
        return t(module);
    }

    async function loadUses(){
        const url  = api(`tags/uses/${tag}`);
        const resp = await fetch(url,{credentials:'include'});
        if (resp.ok){
            uses = await resp.json();
            yikes();
        } else {
            error(resp);
        }
    }

    function goEasy(){
        router.navigate(`/tags/easylist/${tag}`);
    }

    onMount(loadUses);
</script>
<fieldset>
    <legend>
        {t('tag_uses',{tag:tag})}
        <button onclick={goEasy}>{t('easy_list')}</button>
    </legend>
    {#if uses}
    {#each Object.entries(uses) as [module,ids]}
    <h2>{headline(module)}</h2>
    <ul>
        {#each ids as id}
        <li><Reference {module} {id} /></li>
        {/each}
    </ul>
    {/each}
    {/if}
</fieldset>