// src/lib/i18n.ts
// Frontend i18n configuration and utilities

export const locales = ['de', 'en'] as const
export type Locale = (typeof locales)[number]
export const defaultLocale: Locale = 'de'

/**
 * Validate if a string is a valid locale
 */
export function isValidLocale(locale: string): locale is Locale {
  return locales.includes(locale as Locale)
}

/**
 * Get locale from pathname
 * Returns the locale if found, otherwise returns the default locale
 */
export function getLocaleFromPathname(pathname: string): Locale {
  const segments = pathname.split('/').filter(Boolean)
  const firstSegment = segments[0]

  if (firstSegment && isValidLocale(firstSegment)) {
    return firstSegment
  }

  return defaultLocale
}

/**
 * Remove locale prefix from pathname
 */
export function removeLocaleFromPathname(pathname: string): string {
  const locale = getLocaleFromPathname(pathname)
  const segments = pathname.split('/').filter(Boolean)

  if (segments[0] === locale) {
    segments.shift()
  }

  return '/' + segments.join('/')
}

/**
 * Add locale prefix to pathname
 */
export function addLocaleToPathname(pathname: string, locale: Locale): string {
  const cleanPathname = removeLocaleFromPathname(pathname)

  // For default locale, we could optionally skip the prefix
  // But for consistency, we'll always include it
  return `/${locale}${cleanPathname === '/' ? '' : cleanPathname}`
}

/**
 * Get alternate language links for SEO (hreflang)
 */
export function getAlternateLinks(
  pathname: string,
  baseUrl: string,
): { locale: Locale; url: string }[] {
  const cleanPathname = removeLocaleFromPathname(pathname)

  return locales.map((locale) => ({
    locale,
    url: `${baseUrl}/${locale}${cleanPathname === '/' ? '' : cleanPathname}`,
  }))
}

/**
 * Locale display names for UI
 */
export const localeNames: Record<Locale, { native: string; english: string }> = {
  de: { native: 'Deutsch', english: 'German' },
  en: { native: 'English', english: 'English' },
}

/**
 * Get locale direction (for RTL support in future)
 */
export function getLocaleDirection(locale: Locale): 'ltr' | 'rtl' {
  const rtlLocales: Locale[] = []
  return rtlLocales.includes(locale) ? 'rtl' : 'ltr'
}
