// components/TopNav.tsx
"use client";

import Link from "next/link";
import Image from "next/image";
import { usePathname } from "next/navigation";

import { useAuth } from "@/context/AuthContext";
import ThemeToggle from "@/components/ThemeToggle";

function NavLink({
  href,
  children,
}: {
  href: string;
  children: React.ReactNode;
}) {
  const pathname = usePathname();
  const active = pathname === href;

  return (
    <Link
      href={href}
      className={[
        "text-xs font-medium transition-colors",
        active ? "text-zinc-100" : "text-zinc-400 hover:text-zinc-100",
      ].join(" ")}
    >
      {children}
    </Link>
  );
}

export function TopNav() {
  const { user, logout, loading } = useAuth();
  const isAuthenticated = !!user;

  return (
    <header className="border-b border-zinc-200 bg-white/95 dark:border-zinc-800 dark:bg-black/95 backdrop-blur">
      <div className="mx-auto flex max-w-6xl items-center justify-between px-4 py-2">
        {/* Left: Brand / Home */}
        <Link
          href="/"
          className="text-xs font-semibold tracking-[0.2em] uppercase text-zinc-400"
        >
          <Image
            src="/battl/battl-logo-mark-2.svg"
            alt="Battl Builders Logo"
            width={260}
            height={48}
            className="block"
          />
        </Link>

        {/* Right side actions */}
        <div className="flex items-center gap-4">
          <ThemeToggle />

          {loading ? (
            <span className="text-xs text-zinc-500">Checking session…</span>
          ) : isAuthenticated ? (
            <>
              <NavLink href="/vault">Vault</NavLink>

              {/* Email/displayName links to Account */}
              <Link
                href="/account"
                className="hidden text-xs text-zinc-300 hover:text-zinc-100 transition-colors sm:inline"
                title="Account"
              >
                {user.displayName || user.email}
              </Link>

              <button
                type="button"
                onClick={logout}
                className="text-xs font-medium text-zinc-400 hover:text-zinc-100 transition-colors"
              >
                Log Out
              </button>
            </>
          ) : (
            <>
              <NavLink href="/login">Log In</NavLink>

              <Link
                href="/register"
                className="rounded-md border border-amber-400/70 bg-amber-400/10 px-3 py-1.5 text-xs font-semibold text-amber-200 hover:bg-amber-400/20 transition-colors"
              >
                Join Beta
              </Link>
            </>
          )}
        </div>
      </div>
    </header>
  );
}