import { Link } from "react-router-dom";
import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";
import { Button } from "@/components/ui/button";
import type { BacklinkPage } from "@/hooks/useBacklinks";

interface Props {
  backlinks: BacklinkPage[];
}

export default function BacklinkIndicator({ backlinks }: Props) {
  if (backlinks.length === 0) return null;

  return (
    <Popover>
      <PopoverTrigger
        render={<Button variant="ghost" size="sm" className="text-xs text-muted-foreground h-7 px-2" />}
      >
        ← {backlinks.length} backlink{backlinks.length !== 1 ? "s" : ""}
      </PopoverTrigger>
      <PopoverContent className="w-64 p-2" align="end">
        <p className="text-xs font-semibold text-muted-foreground mb-2 px-1">
          Pages linking here
        </p>
        <ul className="space-y-0.5">
          {backlinks.map((page) => (
            <li key={page.name}>
              <Link
                to={`/editor/${page.name}`}
                className="flex items-center gap-1.5 text-sm px-2 py-1 rounded hover:bg-accent"
              >
                <span>{page.title ?? page.name}</span>
                {page.title && (
                  <span className="text-xs text-muted-foreground font-mono">
                    ({page.name})
                  </span>
                )}
              </Link>
            </li>
          ))}
        </ul>
      </PopoverContent>
    </Popover>
  );
}
