<script>
    import { activeField } from './field_sync.svelte.js';
    import { api, target } from '../urls.svelte.js';
    import { t }           from '../translations.svelte.js';

    import Display from './MarkdownDisplay.svelte';

    let {
        editable = true,
        onclick  = evt => {},
        onSet    = newVal => {return true;},
        simple   = false,
        store_id = null,
        type     = 'div',
        value    = $bindable({source:null,rendered:null})
    } = $props();

    let editing   = $state(false);
    let editValue = $state({source:value.source,rendered:value.rendered});
    let start     = 0;
    let stored_source = $state(store_id ? localStorage.getItem(store_id) : null);
    let timer     = null;
    let sheet     = null;

    async function applyEdit(){
        let success = await onSet(editValue.source);
        if (success) {
            value.source   = editValue.source;
            value.rendered = editValue.rendered;
            editing        = false;
        } else resetEdit();
    }

    function doSave(){
        if (store_id) localStorage.removeItem(store_id);
        if (simple){
            onSet(editValue.source);
        } else applyEdit();
    }

    function resetEdit(){
        editing   = false;
        editValue = {source:value.source,rendered:value.rendered};
    }

    function startEdit(){
        activeField.update((n) => n+1);
        editing = editable;
    }

    async function render(){
        const url  = api('markdown/render');
        const resp = await fetch(url,{
            credentials: 'include',
            method     : 'POST',
            body       : editValue.source
        });
        editValue.rendered = await resp.text();
        if (store_id) localStorage.setItem(store_id,editValue.source);
    }

    function typed(ev){
        if (simple) {
            value.source   = editValue.source;
            value.rendered = editValue.rendered;
        }
        if (ev.keyCode == 13 && ev.ctrlKey) doSave();
        if (ev.keyCode == 27) resetEdit();

        if (timer) clearTimeout(timer);
        timer = setTimeout(render,500);
    }

    function measured(evt,duration){
        if (duration < 500){
            onclick(evt);
        } else {
            startEdit();
        }
    }


    function oncontextmenu(evt){
        if (evt.target) {
            evt.preventDefault();
            evt.stopPropagation();
        }
        sheet = evt.sheet ? evt : null; // store position of activated cell to focus after editing starts
        startEdit();
        return false;
    }

    function onmousedown(evt){
        evt.preventDefault();
        start = evt.timeStamp;
    }

    function onmouseup(evt){
        evt.preventDefault();
        measured(evt, evt.timeStamp - start);
    }

    function onresize(evt){
        console.log('onresize()',evt);
    }

    function ontouchstart(evt){
        evt.preventDefault();
        start = evt.timeStamp;
    }

    function ontouchend(evt){
        evt.preventDefault();
        measured(evt, evt.timeStamp - start);
    }

    function restore(ev){
        editValue.source = stored_source;
        stored_source = null;
        render();
    }

    activeField.subscribe((val) => resetEdit());
    if (simple) startEdit();
</script>

<style>
    .markdown{
        position: relative;
    }
    #restore_markdown{
        position: absolute;
        right: 50%;
        top: -10px;
        background: orange;
        color: black;
        padding: 5px;
        border-radius: 5px;
    }
</style>

<div class="markdown {editing || simple ?'editing':''}">
{#if editing || simple}
    <span class="hint">{@html t('markdown_supported')}</span>
    {#if stored_source}
    <span id="restore_markdown" onclick={restore} class="hint">{t('unsaved_content')}</span>
    {/if}
    <textarea bind:value={editValue.source} onkeyup={typed} onresize={onresize} data="test" autofocus={!simple}></textarea>
    <Display classes="preview" bind:markdown={editValue} sheet={sheet} />
    {#if !simple}
    <div class="buttons">
        <button class="cancel" onclick={e => editing = false}>{t('cancel')}</button>
        <button class="save" onclick={doSave}>{t('save')}</button>
    </div>
    {/if}
{:else}
    <Display classes={{editable}} markdown={value} {onclick} {oncontextmenu} title={t('right_click_to_edit')} wrapper={type} />
{/if}
</div>
