/* global process */

/**
 * Central configuration for internationalization (i18n) support
 * This config drives all language-related functionality in the application
 *
 * Moved from @alga-psa/ui to break circular dependency:
 * ui -> analytics -> tenancy -> ui
 */

export const LOCALE_CONFIG = {
  /**
   * The default locale to use when no preference is set
   */
  defaultLocale: 'en',

  /**
   * Array of supported locales
   * Add new languages here to enable them throughout the application
   */
  supportedLocales: ['en', 'fr', 'es', 'de', 'nl', 'it', 'pl', 'pt', 'xx', 'yy'] as const,

  /**
   * Human-readable names for each locale
   * Used in language switcher UI components
   */
  localeNames: {
    en: 'English',
    fr: 'Français',
    es: 'Español',
    de: 'Deutsch',
    nl: 'Nederlands',
    it: 'Italiano',
    pl: 'Polski',
    pt: 'Português',
    xx: 'Pseudo (xx)',
    yy: 'Pseudo (yy)',
  } as const,

  /**
   * Locales that require right-to-left text direction
   * Add locale codes here for RTL languages (e.g., 'ar', 'he')
   */
  rtlLocales: [] as string[],

  /**
   * Cookie configuration for storing user locale preference
   */
  cookie: {
    name: 'locale',
    maxAge: 60 * 60 * 24 * 365, // 1 year
    sameSite: 'lax' as const,
    secure: process.env.NODE_ENV === 'production',
  },
} as const;

/**
 * Type for supported locales derived from config
 */
export type SupportedLocale = typeof LOCALE_CONFIG.supportedLocales[number];

/**
 * Type guard to check if a string is a supported locale
 */
export function isSupportedLocale(locale: string): locale is SupportedLocale {
  return LOCALE_CONFIG.supportedLocales.includes(locale as SupportedLocale);
}

/**
 * Get the best matching locale from a list of preferred locales
 */
export function getBestMatchingLocale(
  preferredLocales: readonly string[],
): SupportedLocale {
  for (const locale of preferredLocales) {
    // Exact match
    if (isSupportedLocale(locale)) {
      return locale;
    }

    // Try language part only (e.g., 'en' from 'en-US')
    const languagePart = locale.split('-')[0];
    if (isSupportedLocale(languagePart)) {
      return languagePart as SupportedLocale;
    }
  }

  return LOCALE_CONFIG.defaultLocale as SupportedLocale;
}

/**
 * Configuration for i18next
 */
export const I18N_CONFIG = {
  debug: process.env.NODE_ENV === 'development',
  fallbackLng: LOCALE_CONFIG.defaultLocale,
  supportedLngs: [...LOCALE_CONFIG.supportedLocales],
  defaultNS: 'common',
  ns: ['common'],
  interpolation: {
    escapeValue: false, // React already escapes values
  },
  load: 'languageOnly' as const, // Don't load region-specific variants
  cleanCode: true,
  nonExplicitSupportedLngs: true,
};

/**
 * Pseudo-locale codes used for QA / local testing only. Translation files
 * remain on disk so developers can force these via cookie/URL, but they are
 * never offered in user-facing language pickers.
 */
export const PSEUDO_LOCALES: ReadonlyArray<SupportedLocale> = ['xx', 'yy'];

/**
 * Locales whose translation packs are still in progress and should not yet be
 * offered in user-facing pickers. Translations remain on disk so existing
 * users who already selected them keep working, and so we can continue
 * iterating on them, but they won't appear as new selections.
 */
export const INCOMPLETE_LOCALES: ReadonlyArray<SupportedLocale> = ['pt'];

/**
 * Filter pseudo-locales and incomplete locales from a list. Use this for any
 * user-facing language picker. Pseudo-locales stay selectable in development
 * builds so translated surfaces can be QA'd visually.
 */
export function filterPseudoLocales(
  locales: readonly SupportedLocale[],
): SupportedLocale[] {
  const includePseudo = process.env.NODE_ENV === 'development';
  return locales
    .filter((l) => includePseudo || !(PSEUDO_LOCALES as readonly string[]).includes(l))
    .filter((l) => !(INCOMPLETE_LOCALES as readonly string[]).includes(l));
}

/**
 * Route prefixes mapped to their required namespaces
 */
export const ROUTE_NAMESPACES = {
  '/client-portal': ['common', 'client-portal'],
  '/client-portal/tickets': ['common', 'client-portal', 'features/tickets'],
  '/client-portal/projects': ['common', 'client-portal', 'features/projects'],
  '/client-portal/billing': ['common', 'client-portal', 'features/billing'],
  '/client-portal/documents': ['common', 'client-portal', 'features/documents'],
  '/client-portal/kb': ['common', 'client-portal', 'features/documents'],
  '/client-portal/appointments': ['common', 'client-portal', 'features/appointments'],
  '/client-portal/request-services': ['common', 'client-portal', 'client-portal/service-requests'],
  '/msp': ['common', 'msp/core', 'msp/dashboard', 'msp/keyboard-shortcuts'],
  '/msp/dashboard': ['common', 'msp/core', 'msp/dashboard'],
  '/msp/surveys': ['common', 'msp/core', 'msp/surveys'],
  '/msp/schedule': ['common', 'msp/core', 'msp/schedule'],
  '/msp/knowledge-base': ['common', 'msp/core', 'features/documents', 'msp/knowledge-base'],
  '/msp/jobs': ['common', 'msp/core', 'msp/jobs'],
  '/msp/tickets': ['common', 'msp/core', 'features/tickets'],
  '/msp/projects': ['common', 'msp/core', 'features/projects'],
  '/msp/billing/credits': ['common', 'msp/core', 'features/billing', 'msp/credits'],
  '/msp/billing': ['common', 'msp/core', 'features/billing', 'msp/quotes', 'msp/reports', 'msp/billing', 'msp/contract-lines', 'msp/contracts', 'msp/invoicing'],
  '/msp/quote-approvals': ['common', 'msp/core', 'features/billing', 'msp/quotes'],
  '/msp/quote-document-templates': ['common', 'msp/core', 'features/billing', 'msp/quotes'],
  '/msp/clients': ['common', 'msp/core', 'msp/clients'],
  '/msp/contacts': ['common', 'msp/core', 'msp/contacts'],
  '/msp/assets': ['common', 'msp/core', 'msp/assets'],
  '/msp/onboarding': ['common', 'msp/core', 'msp/onboarding'],
  '/msp/workflows': ['common', 'msp/core', 'msp/workflows'],
  '/msp/workflows/runs': ['common', 'msp/core', 'msp/workflows'],
  '/msp/workflow-editor': ['common', 'msp/core', 'msp/workflows'],
  '/msp/workflow-control': ['common', 'msp/core', 'msp/workflows'],
  '/msp/technician-dispatch': ['common', 'msp/core', 'msp/dispatch'],
  '/msp/time-entry': ['common', 'msp/core', 'msp/time-entry'],
  '/msp/time-sheet-approvals': ['common', 'msp/core', 'msp/time-entry'],
  '/msp/time-management': ['common', 'msp/core', 'msp/time-entry'],
  '/msp/service-requests': ['common', 'msp/core', 'features/tickets', 'msp/service-requests'],
  '/msp/settings/extensions': ['common', 'msp/core', 'msp/settings', 'msp/extensions'],
  '/msp/settings': ['common', 'msp/core', 'msp/settings', 'msp/keyboard-shortcuts', 'msp/admin', 'msp/email-providers', 'features/projects', 'features/tickets', 'msp/billing-settings', 'msp/service-catalog', 'features/billing', 'msp/calendar', 'msp/integrations'],
  '/msp/profile': ['common', 'msp/core', 'msp/settings', 'msp/profile', 'msp/calendar'],
  '/msp/security-settings': ['common', 'msp/core', 'msp/settings', 'msp/profile'],
  '/msp/platform-updates': ['common', 'msp/core', 'msp/profile'],
  '/msp/extensions': ['common', 'msp/core', 'msp/extensions'],
  '/msp/licenses': ['common', 'msp/core', 'msp/licensing'],
  '/msp/account': ['common', 'msp/core', 'msp/account', 'msp/licensing'],
  '/msp/user-activities': ['common', 'msp/core', 'msp/user-activities', 'msp/workflows', 'features/tickets', 'features/projects', 'msp/schedule'],
} as const;

/**
 * Resolve namespaces for a given route, preferring exact match, then longest prefix match.
 */
export function getNamespacesForRoute(pathname: string): string[] {
  if (!pathname) {
    return ['common'];
  }

  if (Object.prototype.hasOwnProperty.call(ROUTE_NAMESPACES, pathname)) {
    return [...ROUTE_NAMESPACES[pathname as keyof typeof ROUTE_NAMESPACES]];
  }

  let bestMatch: keyof typeof ROUTE_NAMESPACES | null = null;
  for (const route of Object.keys(ROUTE_NAMESPACES) as Array<keyof typeof ROUTE_NAMESPACES>) {
    if (pathname === route || pathname.startsWith(route + '/')) {
      if (!bestMatch || route.length > bestMatch.length) {
        bestMatch = route;
      }
    }
  }

  if (bestMatch) {
    return [...ROUTE_NAMESPACES[bestMatch]];
  }

  return ['common'];
}

/**
 * Paths for translation resources
 */
export const TRANSLATION_PATHS = {
  server: '/locales/{{lng}}/{{ns}}.json',
  client: '/locales/{{lng}}/{{ns}}.json',
} as const;
