"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import { signIn, signOut, useSession } from "next-auth/react";

export default function NavBar() {
  const { data } = useSession();
  const pathname = usePathname();
  const isAdmin = data?.user?.role === "ADMIN" || data?.user?.role === "SUPERADMIN";
  const isSuperAdmin = data?.user?.role === "SUPERADMIN";
  const [logoUrl, setLogoUrl] = useState<string | null>(null);
  const linkClass = (href: string) =>
    pathname === href
      ? "rounded-full bg-slate-900 px-3 py-1 text-white"
      : "rounded-full px-3 py-1 text-slate-700 hover:bg-slate-100";

  useEffect(() => {
    const loadLogo = async () => {
      try {
        const response = await fetch("/api/branding/logo", {
          method: "HEAD",
          cache: "no-store"
        });
        if (response.ok) {
          setLogoUrl(`/api/branding/logo?ts=${Date.now()}`);
        } else {
          setLogoUrl(null);
        }
      } catch {
        setLogoUrl(null);
      }
    };
    loadLogo();
  }, []);

  return (
    <header className="sticky top-0 z-20 border-b border-slate-200/70 bg-white/70 backdrop-blur">
      <div className="mx-auto flex max-w-6xl items-center justify-between px-4 py-4">
        <Link href="/" className="flex items-center gap-3 text-lg font-semibold tracking-tight text-slate-900">
          {logoUrl && (
            <img
              src={logoUrl}
              alt="Vereinskalender Logo"
              className="h-8 w-auto max-w-[140px] object-contain"
              onError={() => setLogoUrl(null)}
            />
          )}
          <span>Vereinskalender</span>
        </Link>
        <nav className="flex items-center gap-3 text-sm">
          {data?.user && (
            <>
              {isAdmin && (
                <>
                  <Link href="/admin" className={linkClass("/admin")}>
                    Admin
                  </Link>
                  <Link href="/admin/users" className={linkClass("/admin/users")}>
                    Registrierungen
                  </Link>
                </>
              )}
              <Link href="/settings" className={linkClass("/settings")}>
                Einstellungen
              </Link>
            </>
          )}
          {data?.user ? (
            <button
              type="button"
              onClick={() => signOut()}
              className="btn-primary"
            >
              Logout
            </button>
          ) : (
            <button
              type="button"
              onClick={() => signIn()}
              className="btn-accent"
            >
              Login
            </button>
          )}
        </nav>
      </div>
    </header>
  );
}
