"use client";

import { usePathname } from "next/navigation";
import { useEffect } from "react";

/**
 * Announce route changes to assistive tech. Without this, screen-reader
 * users see no signal that navigation completed because the view
 * transition is intentionally seamless for sighted users.
 *
 * The announcer also restores the keyboard focus to the top of the new
 * page after navigation, so tab order picks up where the user expects
 * (not stuck on the link they just clicked).
 */
export function RouteAnnouncer() {
  const pathname = usePathname();

  useEffect(() => {
    // Reset focus to the page wrapper so keyboard nav continues from
    // the top, not from the link in the sidebar.
    const target = document.getElementById("page-content") ?? document.body;
    if (target && "tabIndex" in target) {
      (target as HTMLElement).tabIndex = -1;
      (target as HTMLElement).focus({ preventScroll: true });
    }
  }, [pathname]);

  return (
    <div
      role="status"
      aria-live="polite"
      aria-atomic="true"
      className="sr-only"
    >
      {/* Text is intentionally empty — the live region is the
          announcement channel; the actual title is set per page via
          the <h1> rendered inside the layout. */}
    </div>
  );
}
