import { defaultLang, languages, flatTranslations, translations } from './translations';
import type { Lang } from '@/types/i18n';

export type TranslationKey = string;

export function useTranslations(lang: Lang | undefined) {
  const currentLang = lang || defaultLang;
  
  function t(key: TranslationKey, ...args: any[]): any {
    let translation: any = flatTranslations[currentLang][key];
    
    // Fallback to raw translations for objects/arrays
    if (translation === undefined) {
      const keys = key.split('.');
      let current: any = translations[currentLang as keyof typeof translations];
      for (const k of keys) {
        if (current && typeof current === 'object' && k in current) {
          current = current[k];
        } else {
          current = undefined;
          break;
        }
      }
      translation = current;
    }

    if (translation === undefined && currentLang !== defaultLang) {
      translation = flatTranslations[defaultLang][key];
      if (translation === undefined) {
        const keys = key.split('.');
        let current: any = translations[defaultLang as keyof typeof translations];
        for (const k of keys) {
          if (current && typeof current === 'object' && k in current) {
            current = current[k];
          } else {
            current = undefined;
            break;
          }
        }
        translation = current;
      }
    }
    
    if (translation === undefined) {
      console.warn(`Translation key not found: ${key}`);
      return key;
    }
    
    // Replace placeholders with arguments if it's a string
    if (typeof translation === 'string' && args.length > 0) {
      let result = translation;
      args.forEach((arg, index) => {
        result = result.replace(`{${index}}`, String(arg));
      });
      return result;
    }
    
    return translation;
  }

  return t;
}

/**
 * Get localized path
 * Adds language prefix to path if needed
 * 
 * @param path - The path to localize
 * @param lang - The language to localize for
 * @returns The localized path
 */
export function getLocalizedPath(path: string, lang: Lang | undefined): string {
  const currentLang = lang || defaultLang;
  const basePath = import.meta.env.BASE_URL === '/' ? '' : import.meta.env.BASE_URL;

  let newPath = path;
  // Ensure path starts with a slash if it's not an external URL
  if (!newPath.startsWith('/') && !newPath.match(/^https?:\/\//)) {
    newPath = `/${newPath}`;
  }

  // Remove any existing language prefix from the path
  const pathParts = newPath.split('/').filter(p => p);
  if (pathParts.length > 0 && Object.keys(languages).includes(pathParts[0])) {
    newPath = '/' + pathParts.slice(1).join('/');
  }

  // If the path is empty after processing, make it root
  if (newPath === '') newPath = '/';
  
  // Add language prefix if needed
  // If currentLang is not the default language, add the language prefix
  if (currentLang !== defaultLang) {
    newPath = `/${currentLang}${newPath}`;
  }
  // No prefix needed for default language as per astro.config.mjs (prefixDefaultLocale: false)

  // Combine with base path and clean up any double slashes
  const fullPath = `${basePath}${newPath}`;
  return fullPath.replace(/\/\/+/g, '/');
}
