<template>
	<form
		class="writer"
		@submit.prevent="addComment"
	>
		<textarea
			ref="input"
			v-model="body"
			placeholder="Write a new comment"
			class="input"
		/>

		<div class="actions">
			<button
				:disabled="body.length === 0"
				class="button button-submit action submit"
			>Comment</button>

			<button
				v-if="comment"
				type="button"
				class="button button-cancel action cancel"
				@click="$emit('cancel')"
			>Cancel</button>
		</div>
	</form>
</template>

<script setup>
import { ref, onMounted } from 'vue';

import * as api from '../../assets/js/api';
import { reload } from '../../assets/js/navigate';

const props = defineProps({
	comment: {
		type: Object,
		default: null,
	},
	post: {
		type: Object,
		default: null,
	},
});

const body = ref('');
const input = ref(null);

async function addComment() {
	await api.post(`/posts/${props.post.id}/comments`, {
		body: body.value,
		parentId: props.comment?.id,
	});

	reload();
}

onMounted(() => {
	if (props.comment) {
		input.value.focus();
	}
});
</script>

<style scoped>
.writer {
	width: 100%;
	background: var(--background);
	box-sizing: border-box;
	padding: .5rem;
	border-radius: .5rem;
	margin-bottom: .5rem;
}

.input {
	width: 100%;
	margin-bottom: .25rem;
}

.actions {
	display: flex;
	justify-content: flex-start;
}

.action {
	margin-right: .25rem;
}
</style>
