<script module lang="ts">
	import { tv, type VariantProps } from 'tailwind-variants';

	export const dropdownItem = tv({
		base: 'flex w-full cursor-pointer items-center gap-2 border-0 bg-transparent px-[0.7rem] py-[0.55rem] text-left text-inherit no-underline transition-colors duration-150 hover:no-underline',
		variants: {
			danger: {
				false: 'hover:bg-surface-hover dark:hover:bg-[rgb(55_65_81_/_0.5)]',
				true: 'text-danger hover:bg-danger-soft'
			}
		},
		defaultVariants: {
			danger: false
		}
	});

	export type DropdownItemVariants = VariantProps<typeof dropdownItem>;
</script>

<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?: DropdownItemVariants['danger'];
		onclick?: (event: MouseEvent) => void;
		children: Snippet;
	}

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

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

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

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