"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useState } from "react";
import { nav } from "@/lib/nav";
import { Logo } from "./Logo";

export function Nav({ user }: { user: { name?: string | null; image?: string | null; personSlug?: string | null; role: string } }) {
  const pathname = usePathname();
  const [open, setOpen] = useState(false);
  return (
    <header className="sticky top-0 z-40 border-b border-line/70 bg-paper/85 backdrop-blur">
      <div className="mx-auto flex max-w-7xl items-center justify-between px-5 py-3">
        <Link href="/" aria-label="Home"><Logo /></Link>
        <nav className="hidden items-center gap-1 lg:flex">
          {nav.map((n) => {
            const active = pathname === n.href || pathname.startsWith(n.href + "/");
            return (
              <Link key={n.href} href={n.href}
                className={`rounded-full px-3 py-1.5 text-[13px] transition-colors ${active ? "bg-ink text-white" : "text-ink/70 hover:bg-ink/5 hover:text-ink"}`}>
                {n.label}
              </Link>
            );
          })}
        </nav>
        <div className="flex items-center gap-3">
          <Link href="/find" className="hidden md:inline-flex btn btn-soul !py-1.5">Find a team →</Link>
          <Link href="/me" className="flex items-center gap-2" title="Your profile">
            {user.image ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img src={user.image} alt="" className="h-8 w-8 rounded-full object-cover ring-2 ring-white" />
            ) : (
              <span className="grid h-8 w-8 place-items-center rounded-full bg-ink text-xs text-white">{user.name?.[0] ?? "?"}</span>
            )}
          </Link>
          <button className="lg:hidden rounded-full border border-line px-3 py-1.5 text-sm" onClick={() => setOpen((o) => !o)} aria-expanded={open}>
            Menu
          </button>
        </div>
      </div>
      {open && (
        <nav className="lg:hidden border-t border-line bg-paper px-5 py-3 grid grid-cols-2 gap-1">
          {nav.map((n) => (
            <Link key={n.href} href={n.href} onClick={() => setOpen(false)} className="rounded-lg px-3 py-2 text-sm hover:bg-ink/5">
              {n.label}
              <span className="block text-[11px] text-mist">{n.blurb}</span>
            </Link>
          ))}
          <form action="/api/auth/signout" method="post" className="col-span-2 mt-2">
            <button className="btn btn-ghost w-full justify-center">Sign out</button>
          </form>
        </nav>
      )}
    </header>
  );
}
