<script>
	import { onMount, onDestroy } from 'svelte';
	import { applyAction, enhance } from '$app/forms';
	import { base } from '$app/paths';
	import { page } from '$app/stores';
	import { t } from 'svelte-i18n';
	import { writable } from 'svelte/store';
	import { PERMISSIONS } from '$lib/utils/constants';
	import { hasPrivilige } from '$lib/utils/helpers';

	let isMobileMenuOpen = false;

	/** @type{HTMLDivElement} */
	let headerContainer;

	onMount(() => {
		console.log('Page data in Header:', $page);
		document.documentElement.setAttribute('data-theme', $theme);

		document.addEventListener('click', handleClickOutside);
	});

	onDestroy(() => {
		document.removeEventListener('click', handleClickOutside);
	});
	$: {
		console.log('Page data updated:', $page);
	}

	const theme = writable(
		typeof window !== 'undefined' ? localStorage.getItem('theme') || 'dark' : 'dark'
	);

	/**
	 * handle a click outside the menu to close it.
	 * @param {MouseEvent} event
	 */
	function handleClickOutside(event) {
		if (
			isMobileMenuOpen &&
			event.target instanceof Node &&
			!!headerContainer.contains(event.target)
		) {
			isMobileMenuOpen = false;
		}
	}

	function toggleMobileMenu() {
		isMobileMenuOpen = !isMobileMenuOpen;
	}

	function toggleTheme() {
		theme.update((current) => {
			const newTheme = current === 'dark' ? 'bright' : 'dark';
			localStorage.setItem('theme', newTheme);
			document.documentElement.setAttribute('data-theme', newTheme);
			return newTheme;
		});
	}
</script>

<header class="header">
	<div class="header-container" bind:this={headerContainer}>
		<div class="header-left">
			<div class="header-crafted-by-container">
				<!-- <a href="https://tiny-bits.net/">
          <span>Developed by</span><img
            src={Developer}
            alt="Alexander Stölting"
          /> -->
				<!-- </a> -->
			</div>
		</div>
		<div class="mobile-menu-container">
			<button
				class="mobile-menu-toggle"
				on:click={toggleMobileMenu}
				aria-label="Toggle menu"
				aria-expanded={isMobileMenuOpen}
			>
				<i class="fas {isMobileMenuOpen ? 'fa-times' : 'fa-bars'}"></i>
			</button>
		</div>
		<div class="header-right" class:mobile-menu-open={isMobileMenuOpen}>
			<div class="header-nav-item" class:active={$page.url.pathname === '/'}>
				<a href={`${base}/`}>home</a>
			</div>
			{#if !$page.data.user}
				<div class="header-nav-item" class:active={$page.url.pathname === `${base}/auth/login`}>
					<a href={`${base}/auth/login`}>login</a>
				</div>
				<!-- <div
                    class="header-nav-item"
                    class:active={$page.url.pathname === "/auth/register"}
                >
                    <a href="/auth/register">register</a>
                </div> -->
			{:else}
				<div class="header-nav-item">
					<a href={`${base}/auth/about/${$page.data.user.id}`}>
						<!-- <img
              src={$page.data.user.profile_picture  ? $page.data.user.profile_picture : Avatar}
              alt={`${$page.data.user.first_name} ${$page.data.user.last_name}`}
            /> -->
						{$page.data.user.first_name}
						{$page.data.user.last_name}
					</a>
				</div>
				{#if hasPrivilige($page.data.user, PERMISSIONS.View)}
					<div
						class="header-nav-item"
						class:active={$page.url.pathname.startsWith(`${base}/auth/admin/users`)}
					>
						<a href={`${base}/auth/admin/users`}>{$t('user.management')}</a>
					</div>
				{/if}
				<!-- {#if $page.data.user.is_superuser}
          <div
            class="header-nav-item"
            class:active={$page.url.pathname.startsWith("/auth/admin")}
          >
            <a href="/auth/admin">admin</a>
          </div>
        {/if} -->
				<form
					class="header-nav-item"
					action={`${base}/auth/logout`}
					method="POST"
					use:enhance={async () => {
						return async ({ result }) => {
							await applyAction(result);
						};
					}}
				>
					<button type="submit">logout</button>
				</form>
			{/if}
			<div class="theme-toggle">
				<label class="switch">
					<input type="checkbox" checked={$theme === 'bright'} on:change={toggleTheme} />
					<span class="slider">
						<i class="fas fa-sun"></i>
						<i class="fas fa-moon"></i>
					</span>
				</label>
			</div>
		</div>
	</div>
</header>

<style>
	.theme-toggle {
		display: flex;
		align-items: center;
		margin-left: 20px;
	}

	.switch {
		position: relative;
		display: inline-block;
		width: 60px;
		height: 30px;
	}

	.switch input {
		opacity: 0;
		width: 0;
		height: 0;
	}

	.slider {
		position: absolute;
		cursor: pointer;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: var(--surface0);
		transition: 0.4s;
		border-radius: 30px;
		padding: 4px;
	}

	.slider:before {
		position: absolute;
		content: '';
		height: 22px;
		width: 22px;
		left: 4px;
		bottom: 4px;
		background-color: var(--text);
		transition: 0.4s;
		border-radius: 50%;
	}

	input:checked + .slider {
		background-color: var(--surface0);
	}

	input:checked + .slider:before {
		transform: translateX(30px);
	}

	.fa-sun,
	.fa-moon {
		position: absolute;
		font-size: 16px;
		top: 7px;
		color: var(--text);
		transition: 0.4s;
	}

	.fa-sun {
		left: 7px;
		opacity: 0;
	}

	.fa-moon {
		right: 7px;
		opacity: 1;
	}

	input:checked + .slider .fa-sun {
		opacity: 1;
	}

	input:checked + .slider .fa-moon {
		opacity: 0;
	}
	.mobile-menu-toggle {
		display: none;
		background: none;
		border: none;
		color: var(--text);
		font-size: 1.5rem;
		cursor: pointer;
		padding: 0.5rem;
	}
	.mobile-menu-container {
		display: none;
	}

	.header {
		position: fixed;
		top: 0;
		left: 0;
		z-index: 1;
		box-sizing: border-box;
		width: 100%;
		padding: 3em 0 0;
		background: var(--base);
	}
	.header .header-container {
		width: 100%;
		max-width: calc(1200px + 10em);
		height: 5em;
		display: flex;
		flex-direction: column;
		align-items: center;
		margin: 0 auto;
		background-color: var(--base);
	}
	.header .header-container .header-left {
		display: flex;
		flex-grow: 1;
	}
	.header .header-container .header-left .header-crafted-by-container {
		font-size: 18px;
		font-weight: 300;
	}
	.header .header-container .header-right {
		flex-grow: 1;
		justify-content: space-between;
		letter-spacing: 1px;
		font-weight: 500;
	}
	.header .header-container .header-right .header-nav-item {
		text-transform: uppercase;
		margin-left: 10px;
	}
	.header .header-container .header-right .header-nav-item button {
		all: unset;
		cursor: pointer;
	}

	.header .header-container .header-right .header-nav-item a,
	.header .header-container .header-right .header-nav-item button {
		transition: color 0.3s ease-in-out;
		display: block;
		padding: 20px 0;
		border: none;
		color: var(--subtext0);
	}

	.header .header-container .header-right .header-nav-item:hover a,
	.header .header-container .header-right .header-nav-item:hover button {
		color: var(--lavender);
	}
	@media (min-width: 768px) {
		.header {
			padding: 3em 5rem 0;
		}
		.header .header-container {
			flex-direction: row;
		}
		.header .header-container .header-right {
			display: flex;
			justify-content: flex-end;
		}
		.header .header-container .header-right .header-nav-item {
			margin-left: 26px;
		}
	}
	@media (max-width: 768px) {
		.mobile-menu-container {
			display: block;
			position: relative;
		}

		.header {
			padding: 1rem 0;
		}

		.mobile-menu-toggle {
			display: block;
			position: absolute;
			top: 1rem;
			right: 1rem;
			z-index: 2;
		}

		.header .header-container {
			z-index: 1;
			position: relative;
			padding: 0 1rem;
			flex-direction: column;
			align-items: stretch;
			height: auto;
			padding: 1rem;
		}

		.header-right {
			display: none;
			top: 4rem;
			left: 0;
			right: 0;
			background: var(--base);
			padding: 1rem;
			border-bottom: 1px solid var(--surface1);
		}

		.header-right.mobile-menu-open {
			display: flex;
			flex-direction: column;
			align-items: center;
			gap: 1rem;
			box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
		}

		.header-nav-item {
			width: 100%;
			text-align: center;
			margin: 0;
			padding: 0.5rem 0;
			border-bottom: 1px solid var(--surface1);
		}

		.header-nav-item:last-child {
			border-bottom: none;
		}

		.theme-toggle {
			margin: 1rem 0;
		}

		.header .header-container .header-right {
			flex-direction: column;
			align-items: stretch;
		}

		.header .header-container .header-right .header-nav-item {
			margin: 0;
			text-align: center;
			border-top: 1px solid var(--surface1);
		}

		.header .header-container .header-right .header-nav-item a,
		.header .header-container .header-right .header-nav-item button {
			padding: 1rem 0;
		}

		.theme-toggle {
			display: flex;
			justify-content: center;
			margin: 1rem 0;
		}
	}
</style>
