import { Link, useLocation } from "@tanstack/react-router"; import { ChevronDown } from "lucide-react"; import { useEffect, useLayoutEffect, useRef, useState } from "react"; type NavLinkProps = { text: string; href?: string; variant?: "desktop" | "mobile"; dropdown?: boolean; items?: { text: string; href: string }[]; }; const HeaderNavLink = ({ text, href = "#", variant = "desktop", dropdown = false, items = [], }: NavLinkProps) => { const [open, setOpen] = useState(false); const [alignRight, setAlignRight] = useState(false); const wrapperRef = useRef(null); const menuRef = useRef(null); const location = useLocation(); const pathname = location.pathname; const childIsActive = dropdown && items.length > 0 ? items.some((it) => pathname === it.href || pathname.startsWith(it.href)) : false; const isActive = (!dropdown && pathname === href) || childIsActive; useEffect(() => { if (!open) return; const onDown = (e: MouseEvent) => wrapperRef.current && !wrapperRef.current.contains(e.target as Node) && setOpen(false); document.addEventListener("mousedown", onDown); return () => document.removeEventListener("mousedown", onDown); }, [open]); useLayoutEffect(() => { if (!open || variant !== "desktop") return; const updateAlignment = () => { const wrapper = wrapperRef.current; const menu = menuRef.current; if (!wrapper || !menu) return; const padding = 8; const { right, left } = wrapper.getBoundingClientRect(); const menuWidth = menu.offsetWidth; const spaceRight = window.innerWidth - right - padding; const spaceLeft = left - padding; // If it doesn't fit to the right, and there's more room on the left, align right. setAlignRight(spaceRight < menuWidth && spaceLeft > spaceRight); }; updateAlignment(); window.addEventListener("resize", updateAlignment); return () => window.removeEventListener("resize", updateAlignment); }, [open, variant, items.length]); const base = variant === "mobile" ? "block w-full px-3 py-2 rounded-md transition text-left" : "flex items-center px-5 py-3 h-full transition relative"; const active = variant === "mobile" ? "bg-byu-navy/7 text-byu-navy font-semibold" : "border-b-2 md:border-b-3 border-byu-navy font-semibold"; if (dropdown && items.length > 0) { return (
variant === "desktop" && setOpen(true)} onMouseLeave={() => variant === "desktop" && setOpen(false)} >
    {items.map((item) => { const itemActive = pathname === item.href || pathname.startsWith(item.href); return (
  • setOpen(false)} > {item.text}
  • ); })}
); } return ( {text} ); }; export default HeaderNavLink;