"use client";

import { usePathname, useSearchParams } from "next/navigation";
import { useEffect } from "react";
import { BUILD_ID_PARAM } from "@/lib/update";
import { isRetiredRoute } from "@/lib/update/retired-routes";

function stripBuildId(pathname: string, searchParams: URLSearchParams): string {
  const params = new URLSearchParams(searchParams);
  params.delete(BUILD_ID_PARAM);
  const query = params.toString();
  return query ? `${pathname}?${query}` : pathname;
}

export function useRouteTracker() {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    // A retired route always redirects, so the user is never actually "on" it they are passing through.
    if (isRetiredRoute(pathname)) return;

    const fullPath = stripBuildId(pathname, searchParams);

    const stack = JSON.parse(
      sessionStorage.getItem("routeStack") || "[]"
    );

    if (stack[stack.length - 1] !== fullPath) {
      stack.push(fullPath);
    }

    sessionStorage.setItem("routeStack", JSON.stringify(stack));
  }, [pathname, searchParams]);
}
