<script lang="ts">
	import { resolve } from '$app/paths';
	import type { Component, Snippet } from 'svelte';
	import type { SvelteHTMLElements } from 'svelte/elements';
	import { getContext } from 'svelte';
	interface Props {
		href?: string;
		icon?: Component<SvelteHTMLElements['svg']>;
		danger?: boolean;
		onclick?: (event: MouseEvent) => void;
		children: Snippet;
	}

	let { href, icon, danger = false, onclick, children }: Props = $props();

	const closeDropdown = getContext<(() => void) | undefined>('dropdown-close');

	const handleClick = (event: MouseEvent) => {
		closeDropdown?.();
		onclick?.(event);
	};
</script>

{#if href}
	<a href={resolve(href as '/')} class="item" class:danger onclick={handleClick}>
		{#if icon}
			{@const Glyph = icon}
			<Glyph class="size-4" aria-hidden="true" />
		{/if}
		{@render children()}
	</a>
{:else}
	<button type="button" class="item" class:danger onclick={handleClick}>
		{#if icon}
			{@const Glyph = icon}
			<Glyph class="size-4" aria-hidden="true" />
		{/if}
		{@render children()}
	</button>
{/if}

<style>
	.item {
		--dropdown-item-hover-bg: #f9fafb;
		display: flex;
		width: 100%;
		align-items: center;
		gap: 0.5rem;
		padding: 0.55rem 0.7rem;
		border: 0;
		background: transparent;
		text-align: left;
		text-decoration: none;
		color: inherit;
		cursor: pointer;
		transition: background-color 150ms;
	}

	.item:hover {
		background-color: var(--dropdown-item-hover-bg);
		text-decoration: none;
	}

	@media (prefers-color-scheme: dark) {
		.item {
			--dropdown-item-hover-bg: rgb(55 65 81 / 0.5);
		}
	}

	.danger {
		color: var(--color-danger);
	}

	.danger:hover {
		background-color: var(--color-danger-soft);
	}
</style>
