<script lang="ts">
	import { page } from '$app/state';
	import Icon from '@iconify/svelte';
	import { navigationStore } from '$lib/navigation';
	import { onMount } from 'svelte';
	import { filter, of, tap } from 'rxjs';
	import Avatar from '$lib/components/User/Avatar.svelte';
	import LiquidGlass from './LiquidGlass.svelte';

	const getAddress = (path: string) => 'eve://' + (path === '/' ? 'home' : path.substring(1));

	let path = $derived(page.url.pathname + page.url.search);
	let addressBarValue = $derived(getAddress(path));
	let publicKey = $state('');
	let refreshIndex = $state(0);

	$effect(() => {
		navigationStore.pushState(path);
	});

	onMount(async () => {
		const cleanup = navigationStore.initialize(page.url.pathname);

		try {
			publicKey = await window.eve.getPublicKey();
		} catch (error) {
			console.error('Error getting public key:', error);
		}

		const handleProfileUpdate = (event: CustomEvent) => {
			const { publicKey: updatedPublicKey, avatarUrl: newAvatarUrl } = event.detail;
			if (updatedPublicKey === publicKey) refreshIndex++;
		};
		window.addEventListener('profileUpdated', handleProfileUpdate);

		return () => {
			cleanup?.();
			window.removeEventListener('profileUpdated', handleProfileUpdate);
		};
	});

	function handleSearch() {
		const trimmedValue = addressBarValue.trim();

		if (trimmedValue.startsWith('eve://')) {
			const path = trimmedValue.substring(6); // Remove 'eve://'
			let targetPath = path ? `/${path}` : '/';
			if (targetPath === '/home') targetPath = '/';
			navigationStore.navigateTo(targetPath);
			return;
		}

		if (trimmedValue) navigationStore.navigateTo(`/search?q=${encodeURIComponent(trimmedValue)}`);
		else navigationStore.navigateTo('/');
	}

	const resetAddressBar = () => (addressBarValue = getAddress(path));

	const handleKeyPress = (event: KeyboardEvent) =>
		of(event).pipe(
			filter((event) => event.key === 'Enter'),
			tap(handleSearch)
		);

	function handleBlur() {
		if (!addressBarValue) resetAddressBar();
	}
</script>

<LiquidGlass>
	<div class="flex items-center gap-3 p-3">
		<div class="flex gap-1">
			<button
				class="btn btn-ghost btn-sm btn-circle relative overflow-hidden
               transition-all duration-300 ease-out
               {!$navigationStore.canGoBack
					? 'btn-disabled opacity-30'
					: 'hover:btn-primary hover:scale-105 hover:shadow-lg'}"
				title="Back"
				onclick={() => navigationStore.goBack()}
				disabled={!$navigationStore.canGoBack}
			>
				<Icon icon="mdi:chevron-left" class="w-4 h-4 relative z-10 transition-all duration-200" />
				<div
					class="absolute inset-0 bg-gradient-to-br from-white/10 to-transparent opacity-0 hover:opacity-100 transition-opacity duration-300"
				/>
			</button>
			<button
				class="btn btn-ghost btn-sm btn-circle relative overflow-hidden
               transition-all duration-300 ease-out
               {!$navigationStore.canGoForward
					? 'btn-disabled opacity-30'
					: 'hover:btn-primary hover:scale-105 hover:shadow-lg'}"
				title="Forward"
				onclick={() => navigationStore.goForward()}
				disabled={!$navigationStore.canGoForward}
			>
				<Icon icon="mdi:chevron-right" class="w-4 h-4 relative z-10 transition-all duration-200" />
				<div
					class="absolute inset-0 bg-gradient-to-br from-white/10 to-transparent opacity-0 hover:opacity-100 transition-opacity duration-300"
				/>
			</button>
			<button
				class="btn btn-ghost btn-sm btn-circle hover:btn-secondary"
				title="Home"
				onclick={() => navigationStore.navigateTo('/')}
			>
				<Icon icon="mdi:home" class="w-4 h-4" />
			</button>
		</div>

		<form
			onsubmit={(e) => {
				e.preventDefault();
				handleSearch();
			}}
			class="flex-1 w-full"
		>
			<div class="join w-full">
				<input
					bind:value={addressBarValue}
					onkeyup={handleKeyPress}
					onkeydown={handleKeyPress}
					onkeypress={handleKeyPress}
					onclick={(e) => e.currentTarget.select()}
					onblur={handleBlur}
					type="text"
					placeholder="Search or enter eve:// address..."
					class="input input-bordered join-item w-full focus:outline-offset-0"
				/>
				<button type="submit" class="btn btn-neutral join-item">
					<Icon icon="mdi:magnify" class="w-4 h-4" />
				</button>
			</div>
		</form>
		<div class="flex shrink">
			{#if publicKey}
				<button
					class="btn btn-ghost btn-circle p-1 hover:scale-105 transition-transform"
					onclick={() => navigationStore.navigateTo('/profile')}
					title="Profile"
				>
					<Avatar pubkey={publicKey} {refreshIndex} />
				</button>
			{/if}
		</div>
	</div>
</LiquidGlass>
