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

	export const dropdownItem = tv({
		base: "w-full justify-start rounded-none p-2 text-left focus-visible:-outline-offset-2",
		variants: {
			danger: {
				false: "",
				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";
	import Button from "./Button.svelte";

	interface Props {
		href?: string;
		icon?: Component<SvelteHTMLElements["svg"]>;
		danger?: DropdownItemVariants["danger"];
		onclick?: (event: MouseEvent) => void;
		/** Button hugs its children, so a two-column row needs `[&>span]:w-full` here. */
		class?: string;
		children: Snippet;
	}

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

	const closeDropdown = getContext<(() => void) | undefined>("dropdown-close");
	const registerItem = getContext<((el: HTMLElement) => () => void) | undefined>(
		"dropdown-register"
	);

	let el = $state<HTMLAnchorElement | HTMLButtonElement>();

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

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

<Button
	bind:ref={el}
	variant="ghost"
	href={href ? resolve(href as "/") : undefined}
	class={classes}
	{icon}
	role="menuitem"
	tabindex={-1}
	onclick={handleClick}
>
	{@render children()}
</Button>
