<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 bg-transparent p-2 text-left no-underline hover:no-underline",
		variants: {
			danger: {
				false: "hover:bg-background-subtle dark:hover:bg-[rgb(55_65_81/0.5)]",
				true: "text-foreground-danger hover:bg-background-danger-subtle"
			}
		},
		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 registerItem = getContext<((el: HTMLElement) => () => void) | undefined>(
		"dropdown-register"
	);

	let el = $state<HTMLElement>();

	$effect(() => {
		if (!el || !registerItem) return;
		return registerItem(el);
	});

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

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