"use client";

import { resolvePath, retiredTarget } from "@/lib/update/retired-routes";

// "Back" pops useRouteTracker's route stack, not browser history.

const ROUTE_STACK_KEY = "routeStack";
export const HOME = "/home";

interface BackRouter {
  replace(href: string): void;
}

/** The screen a stack entry actually lands on: pathname, retirement followed. */
function screenOf(entry: string): string {
  return resolvePath(entry.split("?")[0]);
}

/** Rewrites an entry that points at a retired route to point straight at its replacement, keeping the query. */
function directTarget(entry: string): string {
  const [path, query] = entry.split("?");
  const moved = retiredTarget(path);
  if (!moved) return entry;
  return query ? `${moved}?${query}` : moved;
}

export function navigateBack(router: BackRouter): void {
  try {
    if (typeof window === "undefined") {
      router.replace(HOME);
      return;
    }

    const raw = sessionStorage.getItem(ROUTE_STACK_KEY);

    if (!raw) {
      router.replace(HOME);
      return;
    }

    const stack = JSON.parse(raw);

    if (!Array.isArray(stack) || stack.length <= 1) {
      router.replace(HOME);
      return;
    }

    // Drop the entry for the screen we are on.
    stack.pop();

    // Then keep dropping any entry that is the SAME SCREEN as this one.
    const current = screenOf(window.location.pathname);
    while (stack.length) {
      const candidate = stack[stack.length - 1];
      if (typeof candidate !== "string") { stack.pop(); continue; }
      if (screenOf(candidate) === current) { stack.pop(); continue; }
      break;
    }

    if (!stack.length) {
      sessionStorage.setItem(ROUTE_STACK_KEY, JSON.stringify([]));
      router.replace(HOME);
      return;
    }

    const prev = stack[stack.length - 1];
    sessionStorage.setItem(ROUTE_STACK_KEY, JSON.stringify(stack));
    router.replace(directTarget(prev));
  } catch {
    router.replace(HOME);
  }
}
