// Path: Frontend/src/components/Dropdown.tsx

import { createSignal, createUniqueId, Show, type JSX, type ParentComponent } from "solid-js";
import { Portal } from "solid-js/web";
import styles from "./Dropdown.module.scss";

interface DropdownProps {
	trigger: (props: { toggle: (e: MouseEvent) => void; isOpen: boolean }) => JSX.Element;
	children: JSX.Element;
	align?: "left" | "right";
}

const Dropdown: ParentComponent<DropdownProps> = (props) => {
	const [isOpen, setIsOpen] = createSignal(false);

	const anchorName = `--anchor-${createUniqueId()}`;

	const toggle = (e: MouseEvent) => {
		e.preventDefault();
		e.stopPropagation();
		setIsOpen(!isOpen());
	};

	const close = () => setIsOpen(false);

	return (
		<>
			<div class={styles.triggerWrapper} style={{ "--anchor-name": anchorName }}>
				{props.trigger({ toggle, isOpen: isOpen() })}
			</div>

			<Show when={isOpen()}>
				<Portal>
					<div class={styles.backdrop} onClick={close} />

					<div class={`${styles.menu} ${props.align === "left" ? styles.left : styles.right}`} style={{ "--anchor-target": anchorName }} onClick={close}>
						{props.children}
					</div>
				</Portal>
			</Show>
		</>
	);
};

export default Dropdown;
