"use client";

import { useSectionStore } from "@/stores/sectionStore";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

export default function SectionDropdown() {
  const { sections } = useSectionStore();
  if (!sections || sections.length === 0) return null;

  return (
    <DropdownMenu>
      <DropdownMenuTrigger className="px-3 py-2 rounded-md text-sm hover:bg-accent hover:text-accent-foreground">
        页面目录
      </DropdownMenuTrigger>
      <DropdownMenuContent className="w-56">
        <DropdownMenuGroup>
          {sections.map((s) => (
            <DropdownMenuItem key={s.id}
              onClick={() => {
                const el = document.getElementById(s.id);
                if (!el) return;
                const rect = el.getBoundingClientRect();
                const top = rect.top + window.scrollY - 80;
                window.scrollTo({ top, behavior: "smooth" });
                history.replaceState(null, "", `#${s.id}`);
              }}
            >
              {s.name}
            </DropdownMenuItem>
          ))}
        </DropdownMenuGroup>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}