<script>
    import { activeField } from './field_sync.svelte.js';

    let {
        editable = false,
        currency,
        onSet = (newVal) => {},
        value = $bindable(null)
    } = $props();

    let editing   = $state(false);
    let editValue = value/100;

    async function applyEdit(){
        let success = await onSet(editValue * 100);
        if (success) value = editValue * 100;
        editing = false;
    }

    function resetEdit(){
        editValue = value/100;
        editing   = false;
    }

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

    function typed(ev){
        if (ev.keyCode == 13) applyEdit();
        if (ev.keyCode == 27) resetEdit();
    }

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

<style>
    input{width:100px}
    div{
        min-width:  40px;
        min-height: 20px;
    }
    .editable:hover{
        border: 1px dotted;
    }
</style>

{#if editable && editing}
<input type="number" step=".01" bind:value={editValue} onkeyup={typed} />&nbsp;{currency}
{:else}
<div onclick={startEdit} class={{editable}}>{Number(value/100).toFixed(2)}&nbsp;{currency}</div>
{/if}

