<% 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} />;
}

/**
 * Is this href a path on THIS site? Exactly one leading slash.
 *
 *   '/cart'  '/'  '/products?page=2'  '?page=2'   → internal (client-side nav)
 *   '//cdn.example.com/x'  '/\evil.example'        → NOT internal: browsers read
 *     both as a protocol-relative URL, i.e. another origin
 *   'https://…'  'mailto:'  'tel:'  '#anchor'      → NOT internal
 */
function isInternalHref(href: string): boolean {
  if (href.startsWith('?')) return true;
  return href.startsWith('/') && !href.startsWith('//') && !href.startsWith('/\\');
}

export type SmartLinkProps = Omit<ComponentProps<'a'>, 'href'> & {
  /** Anything a CMS or a merchant can type into a menu: a path, a URL, `mailto:`, `tel:`, `#id`. */
  href: string;
  prefetch?: boolean | null;
  replace?: boolean;
  scroll?: boolean;
};

/**
 * One link component for hrefs whose shape you do not control — menu items,
 * footer columns, announcement bars, merchant-written URLs.
 *
 * - `/path` (single leading slash) → the locale-aware {@link Link}: client-side
 *   navigation, no full page reload, locale prefix applied exactly as `Link`
 *   does.
 * - `https://…`, `http://…`, `mailto:`, `tel:`, `#anchor`, `//host/…` and anything
 *   with `target="_blank"` → a plain `<a>`. (An internal path that opens in a
 *   new tab still gets its locale prefix: a new tab is a full page load, so
 *   there is no client navigation to preserve.)
 *
 * Do NOT write `<a href={item.url}>` in `src/ui`: a raw anchor reloads the whole
 * page on every click, which is exactly what this component exists to avoid.
 * The lint rule in `.eslintrc.json` enforces it.
 */
export function SmartLink({ href, prefetch, replace, scroll, rel, ...rest }: SmartLinkProps) {
  const pathname = usePathname();
  const locale = getLocale(pathname);
  const opensNewTab = rest.target === '_blank';
  const safeRel = rel ?? (opensNewTab ? 'noopener noreferrer' : undefined);

  if (isInternalHref(href)) {
    const localized = localizePath(href, locale);
    if (!opensNewTab) {
      return (
        <NextLink
          href={localized}
          prefetch={prefetch}
          replace={replace}
          scroll={scroll}
          rel={safeRel}
          {...rest}
        />
      );
    }
    return <a href={localized} rel={safeRel} {...rest} />;
  }
  return <a href={href} rel={safeRel} {...rest} />;
}

/**
 * The current path without its locale prefix: `/he/cart` and `/cart` are both
 * `/cart`. For "which page am I on" checks that must work in every language.
 */
export function usePathnameWithoutLocale(): string {
  return stripLocale(usePathname() ?? '/');
}

/**
 * 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';

import NextLink from 'next/link';
import { usePathname } from 'next/navigation';
import type { ComponentProps } from 'react';

export { default as Link } from 'next/link';
export { useRouter } from 'next/navigation';

/** Is this href a path on THIS site? Exactly one leading slash (see the multi-language build). */
function isInternalHref(href: string): boolean {
  if (href.startsWith('?')) return true;
  return href.startsWith('/') && !href.startsWith('//') && !href.startsWith('/\\');
}

export type SmartLinkProps = Omit<ComponentProps<'a'>, 'href'> & {
  /** Anything a CMS or a merchant can type into a menu: a path, a URL, `mailto:`, `tel:`, `#id`. */
  href: string;
  prefetch?: boolean | null;
  replace?: boolean;
  scroll?: boolean;
};

/**
 * One link component for hrefs whose shape you do not control — menu items,
 * footer columns, announcement bars, merchant-written URLs.
 *
 * - `/path` (single leading slash) → Next's `Link`: client-side navigation, no
 *   full page reload.
 * - `https://…`, `http://…`, `mailto:`, `tel:`, `#anchor`, `//host/…` and anything
 *   with `target="_blank"` → a plain `<a>`.
 *
 * Do NOT write `<a href={item.url}>` in `src/ui`: a raw anchor reloads the whole
 * page on every click, which is exactly what this component exists to avoid.
 * The lint rule in `.eslintrc.json` enforces it.
 */
export function SmartLink({ href, prefetch, replace, scroll, rel, ...rest }: SmartLinkProps) {
  const opensNewTab = rest.target === '_blank';
  const safeRel = rel ?? (opensNewTab ? 'noopener noreferrer' : undefined);

  if (isInternalHref(href) && !opensNewTab) {
    return (
      <NextLink
        href={href}
        prefetch={prefetch}
        replace={replace}
        scroll={scroll}
        rel={safeRel}
        {...rest}
      />
    );
  }
  return <a href={href} rel={safeRel} {...rest} />;
}

/** The current path. (A single-language store has no locale prefix to strip.) */
export function usePathnameWithoutLocale(): string {
  return usePathname() ?? '/';
}
<% } %>
