<script setup>
import { inject, reactive } from 'vue';

import Checkbox from '#/components/form/checkbox.vue';

import { patch } from '#/src/api.js';

const pageContext = inject('pageContext');
const { user } = pageContext;

const settings = reactive({
	alertNotificationsEnabled: true,
	alertEmailsEnabled: true,
	alertEmailsFrequency: null,
	...user.settings,
});

async function updateSettings() {
	await patch('/me/settings', settings);
}
</script>

<template>
	<form
		class="profile-section"
		@submit.prevent
	>
		<div class="setting noflip">
			<span class="setting-label">
				<strong class="setting-title">Enable alert notifications</strong>
				<span class="setting-description">Your alerts can trigger notifications in traxxx</span>
			</span>

			<span class="setting-value">
				<Checkbox
					:checked="settings.alertNotificationsEnabled"
					@change="(checked) => { settings.alertNotificationsEnabled = checked; updateSettings(); }"
				/>
			</span>
		</div>

		<div class="setting noflip">
			<span class="setting-label">
				<strong class="setting-title">Enable alert e-mails</strong>
				<span class="setting-description">Your alerts can trigger e-mails</span>
			</span>

			<span class="setting-value">
				<Checkbox
					:checked="settings.alertEmailsEnabled"
					@change="(checked) => { settings.alertEmailsEnabled = checked; updateSettings(); }"
				/>
			</span>
		</div>

		<div class="setting">
			<span class="setting-label">
				<strong class="setting-title">Alert e-mail frequency</strong>
				<span class="setting-description">Alert e-mails are sent immediately, or accumulated and sent periodically</span>
			</span>

			<span class="setting-value">
				<select
					v-model="settings.alertEmailsFrequency"
					class="input"
					@change="updateSettings"
				>
					<option :value="null">Immediately</option>
					<option value="daily">Daily</option>
					<option value="weekly">Weekly</option>
					<option value="monthly">Monthly</option>
				</select>
			</span>
		</div>
	</form>
</template>

<style scoped>
.input {
	background: var(--background);
}

.profile-section .heading {
	margin: .5rem 1rem 0 1rem;
}

.setting {
	width: 100%;
	display: flex;
	justify-content: space-between;
	align-items: center;
	box-sizing: border-box;
	padding: .75rem 1rem;
	border-bottom: solid 1px var(--glass-weak-30);

	&:hover {
		border-color: var(--glass-weak-20);
	}
}

.setting-label {
	display: flex;
	flex-direction: column;
}

.setting-title {
	color: var(--glass-strong-20);
	margin-bottom: .25rem;
}

.setting-description {
	color: var(--glass);
	font-size: .9rem;
}

@media(--small-20) {
	.setting:not(.noflip) {
		flex-direction: column;
		align-items: flex-start;
	}

	.setting-label {
		margin-bottom: .75rem;
	}
}
</style>
