"use client";

import { useCallback } from "react";
import { useRouter } from "next/navigation";

/**
 * Back navigation with a fallback route.
 *
 * `router.back()` silently does nothing when the tab has no history entry —
 * e.g. a shared /video/[id] link opened in a new tab or an in-app browser
 * (WhatsApp, Telegram). In that case navigate to `fallback` instead.
 */
export function useGoBack(fallback = "/") {
  const router = useRouter();

  return useCallback(() => {
    if (typeof window !== "undefined" && window.history.length > 1) {
      router.back();
    } else {
      router.push(fallback);
    }
  }, [router, fallback]);
}
