<script>
	import { onMount } from 'svelte';
	import Button from '$lib/components/Button.svelte';

	let { position = 'bottom', button = undefined, children = undefined } = $props();

	let open = $state(false);
	let menuRef = $state(null);
	let buttonRef = $state(null);

	const toggle = () => {
		open = !open;
	};

	const close = () => {
		open = false;
	};

	onMount(() => {
		const handleClickOutside = (event) => {
			if (
				open &&
				menuRef &&
				!menuRef.contains(event.target) &&
				buttonRef &&
				!buttonRef.contains(event.target)
			) {
				close();
			}
		};

		const handleEscape = (event) => {
			if (event.key === 'Escape' && open) {
				close();
			}
		};

		document.addEventListener('click', handleClickOutside);
		document.addEventListener('keydown', handleEscape);

		return () => {
			document.removeEventListener('click', handleClickOutside);
			document.removeEventListener('keydown', handleEscape);
		};
	});
</script>

<div class="menu-container">
	<div class="btncont" bind:this={buttonRef}>
		{#if button}
			{@render button({ toggle, open })}
		{:else}
			<!-- Default three-dots button -->
			<Button fill={true} style="iconbutton" onclick={toggle}>
				<div class="icon-container">
					<svg
						xmlns="http://www.w3.org/2000/svg"
						width="20"
						height="20"
						fill="currentColor"
						viewBox="0 0 16 16"
					>
						<path
							d="M9.5 13a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0zm0-5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0zm0-5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0z"
						/>
					</svg>
				</div>
			</Button>
		{/if}
	</div>

	{#if open}
		<div
			class="menu-items"
			class:top={position === 'top'}
			class:bottom={position === 'bottom'}
			class:left={position === 'left'}
			class:right={position === 'right'}
			bind:this={menuRef}
		>
			{#if children}
				{@render children({ close })}
			{/if}
		</div>
	{/if}
</div>

<style>
	.btncont {
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.menu-container {
		height: 100%;
		position: relative;
		display: inline-block;
	}

	.menu-items {
		position: absolute;
		background-color: var(--light);
		border: 2px solid var(--light-accent);
		border-radius: 5px;
		min-width: 120px;
		z-index: 1000;
		padding: 0.5rem 0;
	}

	.menu-items.bottom {
		top: 100%;
		left: 0;
		margin-top: 4px;
	}

	.menu-items.top {
		bottom: 100%;
		left: 0;
		margin-bottom: 4px;
	}

	.menu-items.left {
		top: 0;
		right: 100%;
		margin-right: 4px;
	}

	.menu-items.right {
		top: 0;
		left: 100%;
		margin-left: 4px;
	}
	svg {
		height: 100%;
	}
	.icon-container {
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.icon-container:hover svg {
		fill: var(--accent);
	}
</style>
