<template>
	<div class="page">
		<header class="header">
			<h2 class="title">
				<a
					:href="`/s/${shelf.slug}`"
					class="nolink"
				>s/{{ shelf.slug }}</a>
			</h2>
		</header>

		<div class="body">
			<slot />

			<div class="sidebar">
				<h4 class="sidebar-title">{{ shelf.slug }}</h4>

				<button
					v-if="subscribed"
					class="button button-submit subscribe"
					@click="unsubscribe"
				>Unsubscribe</button>

				<button
					v-else
					class="button button-submit subscribe"
					@click="subscribe"
				>Subscribe</button>

				<form
					class="form compose"
					@submit.prevent="submitPost"
				>
					<div class="form-row">
						<input
							v-model="title"
							placeholder="Title"
							class="input"
						>
					</div>

					<div class="form-row">
						<input
							v-model="link"
							class="input"
							placeholder="Link"
						>
					</div>

					<div class="form-row">
						<textarea
							v-model="body"
							placeholder="Body"
							class="input body"
						/>
					</div>

					<div class="form-actions">
						<button
							class="button button-submit"
							:disabled="!body && !link"
						>Post</button>
					</div>
				</form>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref } from 'vue';
import * as api from '../../assets/js/api';
import { navigate } from '../../assets/js/navigate';
import { usePageContext } from '../../renderer/usePageContext';

const { routeParams } = usePageContext();

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

const title = ref();
const link = ref(null);
const body = ref(null);
const subscribed = ref(props.shelf.subscribed);

async function submitPost() {
	const post = await api.post(`/shelves/${routeParams.id}/posts`, {
		title: title.value,
		link: link.value,
		body: body.value,
	});

	navigate(`/s/${props.shelf.slug}/post/${post.id}/${post.slug}`);
}

async function subscribe() {
	subscribed.value = true;
	await api.post(`/shelves/${routeParams.id}/members`);
}

async function unsubscribe() {
	subscribed.value = false;
	await api.delete(`/shelves/${routeParams.id}/members`);
}
</script>

<style scoped>
.page {
	display: flex;
	flex-direction: column;
	padding: 1rem
}

.body {
	display: flex;
}

.content {
	width: 100%;
	display: flex;
	flex-grow: 1;
}

.header {
	padding: 1rem;
	border-radius: .25rem;
	margin-bottom: .5rem;
	background: var(--background);
}

.title {
	margin: 0;
	font-size: 1.25rem;
}

.sidebar {
	background: var(--background);
	width: 20rem;
	padding: .5rem;
	border-radius: .25rem;
	margin-left: .5rem;
}

.sidebar-title {
	margin: 0 0 1rem 0;
	font-size: 1.25rem;
}

.subscribe {
	width: 100%;
	margin-bottom: 1rem;
}
</style>
