<script lang="ts">
	import { debounce } from 'lodash';
	import { createEventDispatcher } from 'svelte';
	import { useEntity } from '$lib/entity';
	import type { WidgetChange } from '$lib/types/base';
	import LabelBorder from './LabelBorder.svelte';
	const dispatch = createEventDispatcher<{ change: WidgetChange }>();

	export let address: string;

	$: ({ entity } = useEntity(address));

	$: notes = $entity?.get('NOTE')?.toString();

	let contentEl: HTMLDivElement;

	const update = debounce(() => {
		dispatch('change', {
			type: 'upsert',
			attribute: 'NOTE',
			value: { t: 'String', c: contentEl.innerText }
		});
	}, 500);
</script>

<LabelBorder hide={!notes?.length}>
	<span slot="header">Notes</span>
	<div class="notes" contenteditable on:input={update} bind:this={contentEl}>
		{notes ? notes : ''}
	</div>
</LabelBorder>

<style lang="scss">
	.notes {
		background: var(--background);
		border-radius: 4px;
		padding: 0.5em !important;
	}
</style>
