<% if (i18nEnabled) { %>
'use client';

import React, { useMemo, useCallback } from 'react';
import NextLink from 'next/link';
import { useRouter as useNextRouter, usePathname } from 'next/navigation';
import type { ComponentProps } from 'react';

const supportedLocales = <%- supportedLocales %>;
const defaultLocale = '<%= defaultLocale %>';

function getLocale(pathname: string): string {
  const segment = pathname.split('/')[1];
  return supportedLocales.includes(segment) ? segment : defaultLocale;
}

function stripLocale(path: string): string {
  if (!path.startsWith('/')) return path;
  const firstSeg = path.split('/')[1];
  if (supportedLocales.includes(firstSeg)) {
    return path.slice(`/${firstSeg}`.length) || '/';
  }
  return path;
}

// As-needed locale prefix:
//   defaultLocale → no prefix (/foo)
//   other locale  → /{locale}/foo
// Any incoming path is first stripped of an existing locale segment so we
// never double-prefix even if callers already localized.
function localizePath(path: string, locale: string): string {
  if (!path.startsWith('/')) return path;
  const bare = stripLocale(path);
  if (locale === defaultLocale) return bare;
  return bare === '/' ? `/${locale}` : `/${locale}${bare}`;
}

/**
 * Locale-aware Link — automatically prepends current locale to href.
 */
export function Link({ href, ...props }: ComponentProps<typeof NextLink>) {
  const pathname = usePathname();
  const locale = getLocale(pathname);
  const localizedHref =
    typeof href === 'string' ? localizePath(href, locale) : href;
  return <NextLink href={localizedHref} {...props} />;
}

/**
 * Locale-aware useRouter — push/replace automatically prepend locale.
 * Returns a stable reference to avoid infinite re-render loops when used
 * in useEffect dependency arrays.
 */
export function useRouter() {
  const router = useNextRouter();
  const pathname = usePathname();
  const locale = getLocale(pathname);

  const push = useCallback(
    (url: string, options?: Parameters<typeof router.push>[1]) => {
      return router.push(localizePath(url, locale), options);
    },
    [router, locale]
  );

  const replace = useCallback(
    (url: string, options?: Parameters<typeof router.replace>[1]) => {
      return router.replace(localizePath(url, locale), options);
    },
    [router, locale]
  );

  return useMemo(
    () => ({ ...router, push, replace }),
    [router, push, replace]
  );
}
<% } else { %>
/* Single-language store — re-export Next.js navigation as-is */
'use client';

export { default as Link } from 'next/link';
export { useRouter } from 'next/navigation';
<% } %>
