"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useUnconfiguredNodes } from "@/lib/useNodes";
import { useUnacknowledgedAlerts } from "@/lib/useAlerts";
import { useAuth } from "@/components/AuthProvider";

const links = [
  { href: "/dashboard",  label: "Dashboard" },
  { href: "/nodes",      label: "Nodes" },
  { href: "/systems",    label: "Systems" },
  { href: "/calls",      label: "Calls" },
  { href: "/incidents",  label: "Incidents" },
  { href: "/map",        label: "Map" },
  { href: "/alerts",     label: "Alerts" },
];

const adminLinks = [
  { href: "/tokens", label: "Tokens" },
  { href: "/admin",  label: "Admin" },
];

export function Nav() {
  const { user, isAdmin, signOut } = useAuth();
  const pathname = usePathname();
  const { nodes: pending } = useUnconfiguredNodes();
  const unackedAlerts = useUnacknowledgedAlerts();

  if (!user) return null;

  return (
    <nav className="border-b border-gray-800 bg-gray-950 px-6 py-3 flex items-center gap-6 overflow-x-auto">
      <span className="font-mono font-bold text-white tracking-tight mr-4 shrink-0">DRB</span>
      {[...links, ...(isAdmin ? adminLinks : [])].map(({ href, label }) => (
        <Link
          key={href}
          href={href}
          className={`text-sm font-mono transition-colors shrink-0 ${
            pathname.startsWith(href)
              ? "text-white"
              : "text-gray-500 hover:text-gray-300"
          }`}
        >
          {label}
          {label === "Nodes" && pending.length > 0 && (
            <span className="ml-1.5 inline-flex items-center justify-center w-4 h-4 rounded-full bg-yellow-500 text-gray-950 text-xs font-bold">
              {pending.length}
            </span>
          )}
          {label === "Alerts" && unackedAlerts.length > 0 && (
            <span className="ml-1.5 inline-flex items-center justify-center min-w-[1rem] h-4 rounded-full bg-red-600 text-white text-xs font-bold px-1">
              {unackedAlerts.length}
            </span>
          )}
        </Link>
      ))}
      <div className="ml-auto shrink-0">
        <button
          onClick={signOut}
          className="text-sm font-mono text-gray-500 hover:text-gray-300 transition-colors"
        >
          Sign out
        </button>
      </div>
    </nav>
  );
}
