import { Link, NavLink, useNavigate, useLocation } from "react-router-dom";
import { useAuth } from "../lib/auth";
import { useProfile } from "../lib/profile";
import { Search, LogOut, Upload, Settings as SettingsIcon, Menu, X } from "lucide-react";
import { useState, useEffect } from "react";
import api from "../lib/api";

export const Navbar = () => {
  const { user, logout } = useAuth();
  const { active } = useProfile();
  const nav = useNavigate();
  const location = useLocation();
  const [scrolled, setScrolled] = useState(false);
  const [version, setVersion] = useState("");
  const [mobileOpen, setMobileOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    api.get("/version").then(({ data }) => setVersion(data.version)).catch(() => {});
  }, []);

  // Close the mobile menu on navigation so it never lingers open over the next page.
  useEffect(() => { setMobileOpen(false); }, [location.pathname]);

  const linkClass = ({ isActive }) =>
    `text-sm tracking-wide transition-colors duration-300 ${isActive ? "text-white" : "text-[#8A8A8A] hover:text-white"}`;

  const mobileLinkClass = ({ isActive }) =>
    `block py-3 text-base tracking-wide transition-colors duration-300 ${isActive ? "text-white" : "text-[#8A8A8A]"}`;

  return (
    <header className={`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${scrolled || mobileOpen ? "glass border-b" : ""}`} data-testid="main-navbar">
      <div className="px-6 md:px-12 py-4 flex items-center justify-between">
        <div className="flex items-center gap-10">
          <Link to="/browse" className="flex items-center gap-2" data-testid="nav-logo">
            <span className="font-display text-2xl font-black tracking-tighter text-white">StreamHoard</span>
            <span className="text-[#D9381E] text-2xl leading-none">.</span>
            {version && <span className="text-[10px] text-[#8A8A8A] self-start mt-1" data-testid="nav-version">v{version}</span>}
          </Link>
          {user && (
            <nav className="hidden md:flex items-center gap-7">
              <NavLink to="/browse" className={linkClass} data-testid="nav-browse">Library</NavLink>
              <NavLink to="/shows" className={linkClass} data-testid="nav-shows">Series</NavLink>
              <NavLink to="/my-list" className={linkClass} data-testid="nav-my-list">Shelf</NavLink>
              <NavLink to="/music" className={linkClass} data-testid="nav-music">Music</NavLink>
              <NavLink to="/requests" className={linkClass} data-testid="nav-requests">Wishlist</NavLink>
              {user.is_admin && <NavLink to="/admin" className={linkClass} data-testid="nav-admin">Admin</NavLink>}
            </nav>
          )}
        </div>

        {user ? (
          <div className="flex items-center gap-4">
            <button onClick={() => nav("/search")} className="text-[#8A8A8A] hover:text-white transition-colors duration-300" data-testid="nav-search-button" aria-label="Search">
              <Search size={18} strokeWidth={1.5} />
            </button>
            {user.is_admin && (
              <button onClick={() => nav("/admin/upload")} className="hidden sm:flex items-center gap-2 text-xs uppercase tracking-[0.2em] text-[#8A8A8A] hover:text-white transition-colors duration-300" data-testid="nav-upload-button">
                <Upload size={14} strokeWidth={1.5} /> Upload
              </button>
            )}
            <button onClick={() => nav("/settings")} className="hidden sm:flex items-center gap-2 text-xs uppercase tracking-[0.2em] text-[#8A8A8A] hover:text-white transition-colors duration-300" data-testid="nav-settings-button">
              <SettingsIcon size={14} strokeWidth={1.5} /> Settings
            </button>
            <div className="flex items-center gap-3 pl-4 border-l border-[#222]">
              {active && (
                <div className="flex items-center gap-2" data-testid="account-avatar">
                  <span className="hidden sm:inline text-xs text-white">{active.name}</span>
                  <div className="w-8 h-8 flex items-center justify-center text-white text-xs font-medium" style={{ backgroundColor: active.avatar_color || "#D9381E" }}>
                    {active.name?.[0]?.toUpperCase() || "U"}
                  </div>
                </div>
              )}
              <button onClick={() => { logout(); nav("/login"); }} className="hidden md:block text-[#8A8A8A] hover:text-white transition-colors duration-300" data-testid="nav-logout-button" aria-label="Logout">
                <LogOut size={16} strokeWidth={1.5} />
              </button>
            </div>
            <button
              onClick={() => setMobileOpen((v) => !v)}
              className="md:hidden text-white -mr-2 p-2"
              data-testid="nav-mobile-toggle"
              aria-label={mobileOpen ? "Close menu" : "Open menu"}
              aria-expanded={mobileOpen}
            >
              {mobileOpen ? <X size={22} strokeWidth={1.5} /> : <Menu size={22} strokeWidth={1.5} />}
            </button>
          </div>
        ) : (
          <Link to="/login" className="text-sm tracking-wide bg-[#D9381E] hover:bg-[#ED4B32] text-white px-5 py-2 transition-colors duration-300" data-testid="nav-sign-in">Sign in</Link>
        )}
      </div>

      {user && mobileOpen && (
        <nav className="md:hidden glass border-t border-[#222] px-6 pb-6" data-testid="nav-mobile-menu">
          <NavLink to="/browse" className={mobileLinkClass} data-testid="nav-mobile-browse">Library</NavLink>
          <NavLink to="/shows" className={mobileLinkClass} data-testid="nav-mobile-shows">Series</NavLink>
          <NavLink to="/my-list" className={mobileLinkClass} data-testid="nav-mobile-my-list">Shelf</NavLink>
          <NavLink to="/music" className={mobileLinkClass} data-testid="nav-mobile-music">Music</NavLink>
          <NavLink to="/requests" className={mobileLinkClass} data-testid="nav-mobile-requests">Wishlist</NavLink>
          {user.is_admin && <NavLink to="/admin" className={mobileLinkClass} data-testid="nav-mobile-admin">Admin</NavLink>}
          <div className="mt-2 pt-3 border-t border-[#222] flex flex-col gap-1">
            {user.is_admin && (
              <NavLink to="/admin/upload" className={mobileLinkClass} data-testid="nav-mobile-upload">Upload</NavLink>
            )}
            <NavLink to="/settings" className={mobileLinkClass} data-testid="nav-mobile-settings">Settings</NavLink>
            <button onClick={() => { logout(); nav("/login"); }} className="text-left py-3 text-base tracking-wide text-[#8A8A8A]" data-testid="nav-mobile-logout">
              Sign Out
            </button>
          </div>
        </nav>
      )}
    </header>
  );
};

export default Navbar;
