<template>
	<header class="header">
		<nav class="nav">
			<Link href="/">
				<h1 class="title">
					<div
						class="logo"
						v-html="logo"
					/>
				</h1>
			</Link>

			<ul class="nav-list nolist">
				<!--
				<li class="nav-item">
					<Link
						class="link"
						:class="{ active: activePage === 'updates' }"
						href="/updates"
					>Updates</Link>
				</li>
				-->

				<li class="nav-item">
					<Link
						class="link"
						:class="{ active: activePage === 'actors' }"
						href="/actors"
					>Actors</Link>
				</li>

				<li class="nav-item">
					<Link
						class="link"
						:class="{ active: activePage === 'channels' }"
						href="/channels"
					>Channels</Link>
				</li>

				<li class="nav-item">
					<Link
						class="link"
						:class="{ active: activePage === 'tags' }"
						href="/tags"
					>Tags</Link>
				</li>

				<li class="nav-item">
					<Link
						class="link"
						:class="{ active: activePage === 'movies' }"
						href="/movies"
					>Movies</Link>
				</li>
			</ul>
		</nav>

		<div class="header-section">
			<form
				class="search"
				:class="{ focused: searchFocused }"
				@submit.prevent="search"
			>
				<input
					v-model="query"
					type="search"
					placeholder="Search"
					class="input"
					@focus="searchFocused = true"
					@blur="blurSearch"
				>

				<button
					class="search-button"
					data-search
				>
					<Icon icon="search" />
				</button>
			</form>

			<div
				v-if="user"
				class="userpanel"
				:class="{ searching: searchFocused }"
			>
				<VDropdown
					:triggers="['click']"
					:prevent-overflow="true"
					class="notifs-trigger"
				>
					<button
						type="button"
						class="notifs-button"
						:class="{ unseen: unseen > 0 }"
					>
						<Icon
							icon="bell2"
							class="notifs-bell"
						/>

						<span
							v-if="unseen > 0"
							class="notifs-unseen"
						>{{ unseen }}</span>
					</button>

					<template #popper>
						<div class="menu">
							<div class="notifs-header">
								<h4 class="notifs-heading">Notifications</h4>

								<div
									class="notifs-actions"
								>
									<Icon
										icon="stack-check"
										@click="markAllSeen"
									/>

									<Icon
										v-close-popper
										icon="plus3"
										@click="showAlertDialog = true"
									/>
								</div>
							</div>

							<ul class="notifs nolist">
								<li
									v-for="notif in notifications"
									:key="notif.id"
									class="notif"
									:class="{ unseen: !notif.isSeen }"
									@click="markSeen(notif)"
								>
									<a
										:href="`/scene/${notif.scene.id}/${notif.scene.slug}`"
										target="_blank"
										class="notif-body notif-link nolink"
									>
										<span class="notif-details">
											New

											<span
												v-if="notif.matchedTags.length > 0"
												class="notif-tags"
											>{{ notif.matchedTags.map((tag) => tag.name).join(', ') }}</span>

											scene

											<span
												v-if="notif.matchedActors.length > 0"
												class="notif-actors"
											>with {{ notif.matchedActors.map((actor) => actor.name).join(', ') }}</span>

											<span
												v-if="notif.matchedEntity"
												class="notif-entities"
											>for {{ notif.matchedEntity.name }}</span>

											<span
												v-if="notif.matchedExpressions.length > 0"
												class="notif-entities"
											>matching {{ notif.matchedExpressions.map((match) => match.expression).join(', ') }}</span>
										</span>

										<span class="notif-scene">
											<span class="notif-date">{{ formatDate(notif.scene.effectiveDate, 'MMM d') }}</span>
											<span class="notif-title ellipsis">{{ notif.scene.title }}</span>
										</span>
									</a>
								</li>
							</ul>
						</div>
					</template>
				</VDropdown>

				<VDropdown
					:triggers="['click']"
					:prevent-overflow="true"
				>
					<img
						:src="user.avatar"
						class="avatar"
					>

					<template #popper>
						<div class="menu">
							<a
								:href="`/user/${user.username}`"
								class="menu-header ellipsis"
							>{{ user.username }}</a>

							<ul class="menu-list nolist">
								<li class="menu-item">
									<a
										:href="`/user/${user.username}`"
										class="menu-button nolink"
									>
										<Icon icon="user7" />
										Profile
									</a>
								</li>

								<li
									v-if="user.primaryStash"
									class="menu-item"
								>
									<a
										:href="`/stash/${user.username}/${user.primaryStash.slug}`"
										class="menu-button nolink favorites"
									>
										<Icon icon="heart7" />
										Favorites
									</a>
								</li>

								<li
									v-close-popper
									class="menu-item menu-button"
									@click="showSettings = true"
								>
									<Icon icon="equalizer" />
									Settings
								</li>

								<li
									class="menu-button menu-item logout"
									@click="logout"
								><Icon icon="exit2" />Log out</li>
							</ul>
						</div>
					</template>
				</VDropdown>
			</div>

			<div
				v-else-if="allowLogin"
				class="userpanel"
				:class="{ searching: searchFocused }"
			>
				<a
					:href="`/login?r=${encodeURIComponent(currentPath)}`"
					class="login button button-submit nolink"
				>
					<span class="login-text">Log in</span>
					<Icon icon="enter" />
				</a>
			</div>
		</div>

		<Settings
			v-if="showSettings"
			@close="showSettings = false"
		/>

		<AlertDialog
			v-if="showAlertDialog"
			@close="showAlertDialog = false"
		/>
	</header>
</template>

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

import navigate from '#/src/navigate.js';
import { get, patch, del } from '#/src/api.js';
import { formatDate } from '#/utils/format.js';
// import getPath from '#/src/get-path.js';

import Settings from '#/components/settings/settings.vue';
import AlertDialog from '#/components/alerts/create.vue';

import logo from '../../assets/img/logo.svg?raw'; // eslint-disable-line import/no-unresolved

const pageContext = inject('pageContext');

const user = pageContext.user;
const notifications = ref(pageContext.notifications.notifications);
const unseen = ref(pageContext.notifications.unseen);
const done = ref(true);
const query = ref(pageContext.urlParsed.search.q || '');
const allowLogin = pageContext.env.allowLogin;
const searchFocused = ref(false);
const showSettings = ref(false);
const showAlertDialog = ref(false);

const activePage = computed(() => pageContext.urlParsed.pathname.split('/')[1]);
const currentPath = `${pageContext.urlParsed.pathnameOriginal}${pageContext.urlParsed.searchOriginal || ''}`;

function search() {
	navigate('/search', { q: query.value }, { redirect: true });
}

async function fetchNotifications() {
	const res = await get(`/users/${user?.id}/notifications`);

	notifications.value = res.notifications;
	unseen.value = res.unseen;
}

async function markSeen(notif) {
	if (notif.isSeen || !done.value) {
		return;
	}

	done.value = false;

	await patch(`/users/${user?.id}/notifications/${notif.id}`, {
		seen: true,
	});

	await fetchNotifications();

	done.value = true;
}

async function markAllSeen() {
	done.value = false;

	await patch(`/users/${user?.id}/notifications`, {
		seen: true,
	});

	await fetchNotifications();

	done.value = true;
}

async function logout() {
	await del('/session');
	navigate('/login', null, { redirect: true });
}

function blurSearch(event) {
	if (!event.relatedTarget || !Object.hasOwn(event.relatedTarget?.dataset, 'search')) {
		searchFocused.value = false;
	}
}
</script>

<style scoped>
.header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	position: relative;
	z-index: 100; /* make sure shadow shows up above content */
	box-shadow: 0 0 3px var(--shadow-weak-10);
}

.title {
	margin: 0;
	display: inline-block;
}

.logo {
	display: flex;
	width: 8rem;
	box-sizing: border-box;
	padding: .75rem;
	margin-right: 1rem;
	fill: var(--primary);
}

.nav {
	display: flex;
	align-items: center;
}

.nav-item .link {
	font-size: .9rem;
	color: var(--shadow-strong-10);
	box-sizing: border-box;
	padding: 1rem;
	height: 100%;

	&:hover {
		text-decoration: none;
		color: var(--primary);
	}
}

.link {
	font-weight: bold;

	&.active {
		color: var(--primary);
	}
}

.header-section {
	height: 100%;
	display: flex;
	align-items: center;
	margin-left: .5rem;
}

.search {
	height: 2rem;
	display: flex;
	align-items: center;
	border-radius: 1rem;
	background: var(--background-dark-10);
	box-shadow: inset 0 0 3px var(--shadow-weak-40);

	.input {
		width: 14rem;
		padding: .5rem 0 .5rem 1rem;
		border: none;
		margin: 0;
		background: none;

		&:placeholder-shown {
			text-overflow: ellipsis;
		}
	}

	.search-button {
		padding: 0;
		border: none;
		background: none;
	}

	.icon {
		height: 100%;
		padding: 0 .75rem 0 .5rem;
		fill: var(--shadow-weak-10);
	}

	&.focused {
		/*
		border: solid 1px var(--primary-light-10);
		*/
		box-shadow: inset 0 0 3px var(--shadow-weak-30);

		.icon {
			fill: var(--primary);
			cursor: pointer;
		}
	}

	&:last-child {
		/* login disabled */
		margin-right: 1rem;
	}
}

.userpanel {
	height: 100%;
	display: flex;
	align-items: center;
	padding: 0 1rem 0 0;
	font-size: 0;
	cursor: pointer;

	.button-submit {
		margin-left: 1rem;
	}

	&:hover .avatar {
		box-shadow: 0 0 3px var(--shadow-weak-10);
	}
}

.avatar {
	width: 2rem;
	height: 2rem;
	border-radius: .25rem;
	object-fit: cover;
}

.notifs-trigger {
	height: 100%;
}

.notifs-button {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	height: 100%;
	padding: 0 1.25rem;
	background: none;
	border: none;

	&:hover,
	&.unseen {
		cursor: pointer;

		.icon {
			fill: var(--primary);
		}
	}
}

.notifs-bell {
	margin-bottom: .1rem;
}

.notifs-unseen {
	bottom: 0;
	font-size: .65rem;
	font-weight: bold;
	color: var(--primary);
}

.notifs-bell {
	fill: var(--shadow);
}

.notifs {
	width: 30rem;
	height: 20rem;
	max-width: 100%;
	max-height: 100%;
	overflow-y: auto;
	overflow-x: hidden;
}

.notifs-header {
	display: flex;
	justify-content: space-between;
	box-shadow: inset 0 0 3px var(--shadow-weak-30);

	.icon {
		fill: var(--shadow-strong-10);

		&:hover {
			fill: var(--primary);
			cursor: pointer;
		}
	}
}

.notifs-heading {
	font-size: 1rem;
	padding: .75rem 1rem;
	margin: 0;
	font-weight: normal;
}

.notifs-actions {
	align-items: stretch;

	.icon {
		height: 100%;
		padding: 0 .75rem;

		&:last-child {
			padding-right: 1rem;
		}
	}
}

.notif {
	display: flex;
	align-items: center;
	width: 100%;
	overflow: hidden;

	&:not(:last-child) {
		border-bottom: solid 1px var(--shadow-weak-40);
	}

	&:before {
		width: 2.5rem;
		flex-shrink: 0;
		content: '•';
		color: var(--shadow-weak-20);
		text-align: center;
	}

	&.unseen:before {
		color: var(--primary);
	}

	&.unseen:hover:before {
		content: '✓';
	}
}

.notif-body {
	display: flex;
	flex-direction: column;
	flex-grow: 1;
	overflow: hidden;
	box-sizing: border-box;
	font-size: .9rem;
}

.notif-details {
	padding: .5rem 0 .15rem 0;
	box-sizing: border-box;
	color: var(--shadow-strong);
	font-weight: bold;
}

.notif-link {
	overflow: hidden;
}

.notif-scene {
	display: flex;
	padding: .15rem 0 .5rem 0;
}

.notif-date {
	flex-shrink: 0;
	color: var(--shadow-strong-10);

	&:after {
		content: '•';
		padding: 0 .5rem;
		color: var(--shadow-weak-20);
	}
}

.notif-thumb {
	width: 5rem;
	height: 3rem;
	object-fit: cover;
}

.login {
	display: flex;
	align-items: center;

	.icon {
		display: none;
		padding: 0;
		fill: var(--text-light);
	}
}

.menu {
	overflow: hidden;
}

.menu-header {
	display: flex;
	padding: .75rem 1rem;
	border-bottom: solid 1px var(--shadow-weak-30);
	color: var(--shadow-strong-30);
	text-decoration: none;
	font-weight: bold;
}

.menu-item {
	display: block;
}

.menu-button {
	display: flex;
	align-items: center;
	padding: .75rem .5rem .75rem .75rem;
	font-size: 1.1rem;

	.icon {
		fill: var(--shadow);
		margin-right: .75rem;
		transform: translateY(-1px);
	}

	&:hover {
		color: var(--primary);
		cursor: pointer;

		&:not(.logout) .icon {
			fill: var(--primary);
		}

		&.logout {
			color: var(--error);
		}
	}
}

/*
.favorites .icon {
	fill: var(--primary);
}
*/

.logout .icon {
	fill: var(--error);
}

@media(--small) {
	.header-section {
		flex-grow: 1;
	}

	.search {
		flex-grow: 1;
	}

	.search .input {
		width: 0;
		flex-grow: 1;
	}

	.userpanel.searching {
		padding: 0 0 0 1rem;
		width: 0;
	}

	.login-text {
		display: none;
	}

	.login .icon {
		display: block;
	}
}

@media(--small-10) {
	.nav-list {
		display: none;
	}

	.logo {
		margin-right: .75rem;
	}

	.userpanel {
		padding-left: 1rem;
	}
}
</style>
