"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 pathname = routerState.location.pathname;
	const isHomepage = pathname === "/";
	const isKamp = pathname === "/kamp";

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

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

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

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

	if (isKamp) return null;

	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}
		/>
	);
}
