"use client";

import { useRouter } from "next/navigation";
import {
  Bookmark,
  Film,
  Flame,
  Grid3x3,
  History,
  Home,
  Settings,
  Sparkles,
  Tv,
} from "lucide-react";

import { MOVIE_GENRE_IDS, TV_GENRE_IDS } from "@/config/genres";
import { DropdownMenu, type DropdownItem } from "@/components/ui/dropdown";
import { cn } from "@/lib/utils";

/** Genre dropdown — a flat, keyboard-navigable menu of TMDB genre ids. */
export function GenreMenu({ className }: { className?: string }) {
  const router = useRouter();

  const toItems = (base: string, genres: typeof MOVIE_GENRE_IDS): DropdownItem[] =>
    genres.map((genre) => ({
      id: `${base}-${genre.id}`,
      label: genre.name,
      onSelect: () => router.push(`${base}?genre=${genre.id}`),
    }));

  return (
    <div className={cn("flex items-center gap-1", className)}>
      <GenreGroup
        label="Movies"
        icon={<Film className="h-3.5 w-3.5" />}
        items={toItems("/movies", MOVIE_GENRE_IDS)}
      />
      <GenreGroup
        label="TV Shows"
        icon={<Tv className="h-3.5 w-3.5" />}
        items={toItems("/tv", TV_GENRE_IDS)}
      />
    </div>
  );
}

function GenreGroup({
  label,
  icon,
  items,
}: {
  label: string;
  icon: React.ReactNode;
  items: DropdownItem[];
}) {
  return (
    <DropdownMenu
      label={`${label} genres`}
      items={items}
      panelClassName="max-h-[min(60vh,440px)] min-w-[220px] overflow-y-auto"
    >
      {({ open, toggle, id }) => (
        <button
          type="button"
          id={id}
          onClick={toggle}
          aria-expanded={open}
          aria-haspopup="menu"
          className={cn(
            "inline-flex items-center gap-1.5 rounded-pill px-3 py-2 text-sm font-medium transition-colors duration-300",
            open ? "bg-white/12 text-ink" : "text-ink-soft hover:bg-white/8 hover:text-ink",
          )}
        >
          {icon}
          <span className="hidden lg:inline">{label}</span>
          <span className="lg:hidden">Genres</span>
          <svg viewBox="0 0 24 24" className="h-3.5 w-3.5" aria-hidden>
            <path
              fill="none"
              stroke="currentColor"
              strokeWidth="2.2"
              strokeLinecap="round"
              strokeLinejoin="round"
              d="m6 9 6 6 6-6"
            />
          </svg>
        </button>
      )}
    </DropdownMenu>
  );
}

/**
 * Items for the floating navigation bar.
 *
 * `label` is the full name of the destination. It is never rendered as visible
 * text in the bar — that is icons-only — but it is the accessible name, the
 * `title` attribute and the hover/focus tooltip, so it must stay descriptive.
 *
 * `exact` marks routes that must match only on a whole-segment basis, so
 * `/movies` does not stay active on `/movie/550`.
 */
export interface NavItem {
  href: string;
  label: string;
  icon: typeof Home;
  /** Match the path exactly instead of by prefix. */
  exact?: boolean;
}

/**
 * Primary destinations, in the order they appear in the bar.
 *
 * Discovery only. Settings, history, search and the account menu are *not*
 * listed here: they live in the top header (`site-header.tsx`), which is the
 * single place they appear. Keeping them out of this list is what guarantees the
 * bar cannot end up with a second search or profile control.
 */
export const NAV_ITEMS: NavItem[] = [
  { href: "/", label: "Home", icon: Home, exact: true },
  { href: "/movies", label: "Movies", icon: Film },
  { href: "/tv", label: "TV Shows", icon: Tv },
  { href: "/anime", label: "Anime", icon: Sparkles },
  { href: "/genres", label: "Genres", icon: Grid3x3 },
  { href: "/search?sort=trending", label: "Trending", icon: Flame },
  { href: "/my-list", label: "My List", icon: Bookmark },
];

/**
 * Destinations reachable from the header's account menu rather than the bar
 * itself. `Settings` is imported only for this list.
 */
export const SECONDARY_NAV_ITEMS: NavItem[] = [
  { href: "/history", label: "Watch history", icon: History },
  { href: "/settings", label: "Settings", icon: Settings },
];

/**
 * Whether a nav item is the active one for the current path.
 *
 * The `/tv` vs `/tv/1399` problem is handled by exact matching here, and
 * `/movie/…` detail routes deliberately match nothing: they are cinematic and
 * render no navigation at all.
 */
export function isNavItemActive(item: NavItem, pathname: string, search?: string): boolean {
  if (item.exact) return pathname === item.href;
  if (item.href === "/") return false;
  // An item that carries a query string is a view of one page, so it matches on
  // the path plus that query rather than the path alone.
  const [itemPath, itemQuery] = item.href.split("?");
  if (itemQuery) {
    return pathname === itemPath && (search ?? "").includes(itemQuery);
  }
  return pathname === item.href || pathname.startsWith(`${item.href}/`);
}


