import { createUniqueId, Show, type JSX } from "solid-js";
import { ProfileMenu } from "./ProfileMenu";
import { UserNavButton } from "./UserNavButton";
import { createDesktopMenuController } from "./createDesktopMenuController";
import styles from "./UserNav.module.scss";

type UserNavProps = {
	isMobileViewport: boolean;
	isMobileWorkspaceOpen: boolean;
	onToggleMobileWorkspace: VoidFunction;
};

export const UserNav = (props: UserNavProps): JSX.Element => {
	const menuId = createUniqueId();

	return (
		<Show
			when={props.isMobileViewport}
			fallback={<DesktopUserNav />}
		>
			<div class={styles.root}>
				<UserNavButton isOpen={props.isMobileWorkspaceOpen} menuId={menuId} onToggle={props.onToggleMobileWorkspace} />
			</div>
		</Show>
	);
};

const DesktopUserNav = (): JSX.Element => {
	const controller = createDesktopMenuController();
	const menuId = createUniqueId();

	return (
		<div class={styles.root} ref={controller.setRootRef}>
			<UserNavButton isOpen={controller.isOpen()} menuId={menuId} onToggle={controller.toggleMenu} />
			{controller.isOpen() ? <ProfileMenu id={menuId} menuRef={controller.setMenuRef} onSelect={controller.closeMenu} /> : null}
		</div>
	);
};
