<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';
	import { i18n } from '$lib/i18n';
	import { format } from 'date-fns';
	const dispatch = createEventDispatcher<{ change: WidgetChange }>();

	export let address: string;

	let lastSaved: Date | undefined | null;

	$: ({ 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 }
		});
		lastSaved = new Date();
	}, 500);

	function onInput() {
		lastSaved = null;
		update();
	}
</script>

<LabelBorder hide={!notes?.length}>
	<span slot="header">Notes</span>
	<div class="notes" contenteditable on:input={onInput} bind:this={contentEl}>
		{notes ? notes : ''}
	</div>
	<div class="status">
		{#if lastSaved}
			{$i18n.t('Last saved at {{time}}', { time: format(lastSaved, 'HH:mm') })}
		{:else if lastSaved !== undefined}
			{$i18n.t('Waiting for changes...')}
		{/if}
	</div>
</LabelBorder>

<style lang="scss">
	.notes {
		background: var(--background);
		border-radius: 4px;
		padding: 0.66em !important;
		margin: 0.1rem;

		&:focus {
			outline: 1px solid var(--primary-lighter);
		}
	}

	.status {
		font-size: 0.8em;
		opacity: 0.8;
		margin-top: 0.5em;
		margin-right: 0.1rem;
	}
</style>
