"use client";

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

import {
  GLOBAL_NAV_ITEMS,
  isNavItemActive,
  projectNavItems,
  type ActiveNav,
  type NavItem,
} from "@/lib/nav/items";

interface NavItemsProps {
  // 项目内页传 projectId → 展开项目级入口（大纲/伏笔/审稿，UX §3.1）。
  projectId?: string;
  activeNav?: ActiveNav;
  // 抽屉内点链接后关闭抽屉；静态侧栏不传。
  onNavigate?: () => void;
}

// 导航条目列表（桌面静态侧栏与移动抽屉共用，避免渲染漂移）。
export function NavItems({ projectId, activeNav, onNavigate }: NavItemsProps) {
  const pathname = usePathname() ?? "/";
  const scoped = projectId ? projectNavItems(projectId) : [];

  return (
    <ul className="flex flex-col gap-1 px-2">
      {GLOBAL_NAV_ITEMS.map((item) => (
        <NavLink
          key={item.label}
          item={item}
          active={isNavItemActive(item, { pathname, activeNav })}
          onNavigate={onNavigate}
        />
      ))}
      {scoped.length > 0 ? (
        <li
          className="mt-3 px-3 pb-1 text-xs font-semibold uppercase tracking-wide text-ink-soft/60"
          aria-hidden="true"
        >
          本作
        </li>
      ) : null}
      {scoped.map((item) => (
        <NavLink
          key={item.label}
          item={item}
          active={isNavItemActive(item, { pathname, activeNav })}
          onNavigate={onNavigate}
        />
      ))}
    </ul>
  );
}

function NavLink({
  item,
  active,
  onNavigate,
}: {
  item: NavItem;
  active: boolean;
  onNavigate?: () => void;
}) {
  return (
    <li>
      <Link
        href={item.href}
        onClick={onNavigate}
        aria-current={active ? "page" : undefined}
        className={`flex items-center gap-2 rounded px-3 py-2 text-sm ${
          active
            ? "border-l-2 border-cinnabar bg-[var(--color-cinnabar-wash)] text-cinnabar"
            : "text-ink hover:bg-[var(--color-cinnabar-wash)]"
        }`}
      >
        {item.label}
      </Link>
    </li>
  );
}
