<script lang="ts">
    import {dndzone} from 'svelte-dnd-action';
    import {flip} from 'svelte/animate';

    import type { PlanItem } from '../../stores/planStore'
    import PlanInput from './PlanInput.svelte'
    import Text from '../TextInput.svelte';
    import shortid from 'shortid'

    export let items: Array<PlanItem> = [];
    export let onInput: () => void;
    
    const flipDurationMs = 200;

    function handleSort(e: any) {
      let sortedItems: Array<PlanItem> = [];
      
      e.detail.items.forEach((it: PlanItem) => {
        if (it.text.trim().length != 0) {
          sortedItems.push(it);
        }
        
      });

      items = sortedItems;

      onInput();
    }
    
    let newItem: string = "";

    function onInputNewItem() {
      if (newItem.trim().length != 0) {
        items = [...items, {id: shortid.generate(), text: newItem}];
      }
      newItem = "";

      onInput();
    }
    
    function onKeypress(e: KeyboardEvent, ) {
      if(e.key == "Enter") {
        onInputNewItem();
      }
    }
</script>

<div class="w-11/12">
  <Text bind:val={newItem} onInput={onInput} onBlur={onInputNewItem} onKeypress={onKeypress} placeholder={"New Item"}/>
</div>
<section contenteditable="true" use:dndzone={{items, flipDurationMs}} on:consider={handleSort} on:finalize={handleSort}>
      {#each items as item(item.id)}
          <div class="min-h-4" animate:flip={{duration:flipDurationMs}}>
            <div class="w-11/12">
              <PlanInput bind:text={item.text} onInput={onInput}/>
            </div>
          </div>
      {/each}
</section>