import { type ReactNode, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Link, useNavigate } from "react-router";
import { useAuth } from "../hooks/useAuth.ts";

export function AppHeader({ centerSlot }: { centerSlot?: ReactNode }) {
  const { user } = useAuth();
  const navigate = useNavigate();
  const headerRef = useRef<HTMLElement>(null);
  const [showFab, setShowFab] = useState(false);

  useEffect(() => {
    const el = headerRef.current;
    if (!el) return;
    const obs = new IntersectionObserver(
      ([entry]) => setShowFab(!entry.isIntersecting),
      { threshold: 0 },
    );
    obs.observe(el);
    return () => obs.disconnect();
  }, []);

  return (
    <>
      <header
        ref={headerRef}
        className={`app-header${centerSlot ? " app-header--has-center" : ""}`}
      >
        <Link to="/" className="app-header-brand">🚚 gerbeur</Link>

        {centerSlot && <div className="app-header-center">{centerSlot}</div>}

        <nav className="app-header-nav">
          {user
            ? (
              <>
                <Link
                  to={`/users/${user.username}`}
                  className="app-header-user"
                >
                  {user.username}
                </Link>
                <button
                  type="button"
                  className="btn-primary"
                  onClick={() => navigate("/dumps/new")}
                >
                  + New
                </button>
              </>
            )
            : (
              <>
                <button type="button" onClick={() => navigate("/login")}>
                  Log in
                </button>
                <button
                  type="button"
                  className="btn-primary"
                  onClick={() => navigate("/register")}
                >
                  Register
                </button>
              </>
            )}
        </nav>
      </header>

      {user && createPortal(
        <button
          type="button"
          className={`fab-new${showFab ? " fab-new--visible" : ""}`}
          onClick={() => navigate("/dumps/new")}
          aria-label="New dump"
        >
          + New
        </button>,
        document.body,
      )}
    </>
  );
}
