/**
 * Universal Router Hook with BasePath Support
 *
 * Wrapper around Next.js useRouter that automatically handles basePath
 * for static builds served via iframe or subdirectory
 * 
 * IMPORTANT: In Next.js 15 App Router, router.push() does NOT automatically
 * handle basePath (unlike Pages Router). This is a breaking change in App Router.
 * 
 * This hook ensures basePath is always included when navigating, especially
 * important for static exports served via iframe where basePath is critical.
 * 
 * @see https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration
 */

'use client';

import { useRouter as useNextRouter } from 'next/navigation';
import { useCallback, useMemo } from 'react';

/**
 * Get base path from environment variable
 */
function getBasePath(): string {
  if (typeof process === 'undefined') {
    return '';
  }
  return process.env.NEXT_PUBLIC_BASE_PATH || '';
}

/**
 * Add base path to a route path
 */
function withBasePath(path: string, basePath: string): string {
  if (!basePath) {
    return path;
  }
  // Ensure path starts with /
  const normalizedPath = path.startsWith('/') ? path : `/${path}`;
  // Remove trailing slash from basePath
  const normalizedBasePath = basePath.replace(/\/$/, '');
  return `${normalizedBasePath}${normalizedPath}`;
}

/**
 * Router with basePath support
 *
 * Automatically adds basePath to all navigation methods when basePath is configured.
 * In Next.js 15 App Router, router.push() doesn't handle basePath automatically,
 * so this hook uses window.location to ensure basePath is always included.
 *
 * @example
 * ```tsx
 * const router = useCfgRouter();
 *
 * // With basePath='/cfg/admin':
 * router.push('/dashboard');     // Client-side navigation to '/cfg/admin/dashboard'
 * router.replace('/auth');       // Client-side replace with '/cfg/admin/auth'
 * router.hardPush('/dashboard'); // Full page reload to '/cfg/admin/dashboard'
 * router.hardReplace('/auth');   // Full page replace with '/cfg/admin/auth'
 * ```
 */
export function useCfgRouter() {
  const router = useNextRouter();

  // Get basePath and check if we're in static build mode
  const basePath = useMemo(() => getBasePath(), []);
  const isStaticBuild = useMemo(() => {
    return typeof process !== 'undefined' && process.env.NEXT_PUBLIC_STATIC_BUILD === 'true';
  }, []);

  const push = useCallback((href: string, options?: { scroll?: boolean }) => {
    if (basePath) {
      // App Router doesn't handle basePath automatically, use window.location
      window.location.href = withBasePath(href, basePath);
    } else {
      // No basePath configured, use standard router
      router.push(href, options);
    }
  }, [router, basePath]);

  const replace = useCallback((href: string, options?: { scroll?: boolean }) => {
    if (basePath) {
      // App Router doesn't handle basePath automatically, use window.location
      window.location.replace(withBasePath(href, basePath));
    } else {
      // No basePath configured, use standard router
      router.replace(href, options);
    }
  }, [router, basePath]);

  /**
   * Hard push - always uses window.location.href for full page reload
   *
   * Use this for auth redirects where React contexts need to reinitialize.
   * Unlike push(), this ALWAYS triggers a full page reload, ensuring all
   * contexts are reinitialized with fresh state.
   *
   * @example
   * ```tsx
   * // After successful login - contexts need to reload with new auth state
   * router.hardPush('/dashboard');
   * ```
   */
  const hardPush = useCallback((href: string) => {
    window.location.href = withBasePath(href, basePath);
  }, [basePath]);

  /**
   * Hard replace - always uses window.location.replace for full page reload
   *
   * Same as hardPush but replaces current history entry.
   * Use for auth redirects where you don't want back button to return to login.
   *
   * @example
   * ```tsx
   * // After logout - replace so back button doesn't go to protected page
   * router.hardReplace('/auth');
   * ```
   */
  const hardReplace = useCallback((href: string) => {
    window.location.replace(withBasePath(href, basePath));
  }, [basePath]);

  const prefetch = useCallback((href: string) => {
    // Prefetch doesn't need basePath handling, Next.js handles it
    router.prefetch(href);
  }, [router]);

  const back = useCallback(() => {
    router.back();
  }, [router]);

  const forward = useCallback(() => {
    router.forward();
  }, [router]);

  const refresh = useCallback(() => {
    router.refresh();
  }, [router]);

  return {
    push,
    replace,
    hardPush,
    hardReplace,
    prefetch,
    back,
    forward,
    refresh,
  };
}

