import { useEffect } from "react";
import { useLocation } from "react-router-dom";
import { menuSections, isItemActive } from "../ui/navData";

/**
 * Null-rendering helper that keeps the browser tab title in sync with the
 * active navigation item. Scans menuSections in order (first match wins) via
 * the same isItemActive logic the sidebar uses, so detail routes covered by
 * matchPrefix (e.g. /offers/123) inherit their section item's label.
 * No cleanup on unmount — the last title simply persists.
 */
// Labels reused across sections ("Záznam", "Moje historie", "Správa",
// "Přehled") would produce identical tab titles — qualify those with their
// section label so /attendance and /trips tabs stay distinguishable.
const labelCounts = new Map<string, number>();
for (const section of menuSections) {
  for (const item of section.items) {
    labelCounts.set(item.label, (labelCounts.get(item.label) ?? 0) + 1);
  }
}

export default function TitleSync() {
  const { pathname } = useLocation();

  useEffect(() => {
    for (const section of menuSections) {
      const item = section.items.find((candidate) =>
        isItemActive(candidate, pathname),
      );
      if (item) {
        const ambiguous = (labelCounts.get(item.label) ?? 0) > 1;
        document.title = ambiguous
          ? `${item.label} – ${section.label} · BOHA`
          : `${item.label} · BOHA`;
        return;
      }
    }
    document.title = "BOHA Admin";
  }, [pathname]);

  return null;
}
