"use client";

import { useEffect, useState } from "react";
import type { ReactNode } from "react";

type HeaderBehaviorProps = {
  children: ReactNode;
  isHome: boolean;
};

export function HeaderBehavior({ children, isHome }: HeaderBehaviorProps) {
  const [hidden, setHidden] = useState(false);
  const [solid, setSolid] = useState(!isHome);

  useEffect(() => {
    let previousY = window.scrollY;

    const updateHeader = () => {
      const currentY = window.scrollY;
      const scrollingDown = currentY > previousY;

      setSolid(!isHome || currentY > 24);
      setHidden(scrollingDown && currentY > 160);
      previousY = Math.max(currentY, 0);
    };

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

  const className = ["site-header", isHome ? "is-home" : "", solid ? "is-solid" : "is-transparent", hidden ? "is-hidden" : ""]
    .filter(Boolean)
    .join(" ");

  return <header className={className}>{children}</header>;
}
