"use client";

import { useRouterState } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { authClient } from "@/lib/auth-client";
import { Header } from "./Header";

export function SiteHeader() {
	const { data: session } = authClient.useSession();
	const routerState = useRouterState();
	const isHomepage = routerState.location.pathname === "/";

	const [isVisible, setIsVisible] = useState(false);

	useEffect(() => {
		if (!isHomepage) {
			setIsVisible(true);
			return;
		}

		const handleScroll = () => {
			setIsVisible(window.scrollY > 50);
		};

		handleScroll();
		window.addEventListener("scroll", handleScroll, { passive: true });
		return () => window.removeEventListener("scroll", handleScroll);
	}, [isHomepage]);

	if (!session?.user) {
		return <Header isGuest isVisible={isVisible} isHomepage={isHomepage} />;
	}

	const user = session.user as { name: string; role?: string };
	return (
		<Header
			userName={user.name}
			isAdmin={user.role === "admin"}
			isVisible={isVisible}
			isHomepage={isHomepage}
		/>
	);
}
