<script>
    import { onMount } from 'svelte';

    import Bookmark from './Template.svelte';
    import LineEditor from '../../Components/LineEditor.svelte';
    import MarkdownEditor from '../../Components/MarkdownEditor.svelte';
    import Tags        from '../tags/TagList.svelte';

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

    import Editor          from '../../Components/MarkdownEditor.svelte';
    import Template        from './Template.svelte';

    let bookmark = $state(null);
    let { id } = $props();

    async function load(){
        const url  = api(`bookmark/${id}`);
        const resp = await fetch(url,{credentials:'include'});
        if (resp.ok){
            bookmark = await resp.json();
            yikes();
        } else {
            error(resp.text);
        }
    }

    function visit(ev){
        window.open(bookmark.url, '_blank').focus();
    }

    async function update(field,value){
        var url = api(`bookmark/${id}`);
        var res = await patch(url,{[field]:value});
        if (res.ok){
            yikes();
            bookmark = await res.json();
            if (id != bookmark.id){
                id = bookmark.id;
                history.pushState({}, null, `/bookmark/${id}/view`);
            }
            return true;
        }
        error(res);
        return false;
    }

    onMount(load);
</script>

{#if bookmark}
<fieldset>
    <legend>{t('bookmark')} {id}</legend>
    <table class="edit bookmark">
        <tbody>
            <tr>
                <th>{t('URL')}</th>
                <td>
                    <LineEditor value={bookmark.url} editable={true} onSet={url => update('url',url)} />
                    <button onclick={visit}>{t('open')}</button>
                </td>
            </tr>
            <tr>
                <th>{t('description')}</th>
                <td>
                    <MarkdownEditor editable={true} value={bookmark.comment} onSet={desc => update('comment',desc)}/>
                </td>
            </tr>
            <tr>
                <th>{t('tags')}</th>
                <td>
                    <Tags module="bookmark" id={bookmark.id} />
                </td>
            </tr>
        </tbody>
    </table>

</fieldset>
{/if}
