import { ref } from 'vue'

declare global {
  interface Window {
    jingrow: {
      boot?: {
        lang?: string
        __messages?: Record<string, string>
      }
      _messages?: Record<string, string>
      _?: (text: string, replace?: any, context?: string) => string
      __?: (text: string, replace?: any, context?: string) => string
    }
    __?: (text: string, replace?: any, context?: string) => string
  }
}

function jingrowTranslate(txt: string, replace?: any, context: string | null = null): string {
  if (!txt) return txt
  if (typeof txt !== 'string') return txt

  let translated_text = ''
  const key = txt

  if (context && typeof window !== 'undefined' && window.jingrow?._messages) {
    translated_text = window.jingrow._messages[`${key}:${context}`]
  }

  if (!translated_text && typeof window !== 'undefined' && window.jingrow?._messages) {
    translated_text = window.jingrow._messages[key] || txt
  }

  if (!translated_text) {
    translated_text = txt
  }

  if (replace && typeof replace === 'object') {
    Object.keys(replace).forEach(key => {
      const regex = new RegExp(`\\{${key}\\}`, 'g')
      translated_text = translated_text.replace(regex, replace[key])
    })
  }

  return translated_text
}

if (typeof window !== 'undefined') {
  if (!window.jingrow) {
    (window as any).jingrow = {}
  }
  
  window.jingrow._ = jingrowTranslate
  window.jingrow.__ = jingrowTranslate
  
  window.__ = jingrowTranslate
}

export const __ = jingrowTranslate

export const t = jingrowTranslate

export const locale = ref('zh-CN')

export function setLocale(code: string) {
  locale.value = code
  localStorage.setItem('locale', code)
}

export function getCurrentLocale(): string {
  if (typeof window !== 'undefined' && window.jingrow?.boot?.lang) {
    return window.jingrow.boot.lang
  }
  return locale.value
}

export function initLocale() {
  if (typeof window !== 'undefined' && window.jingrow?.boot?.lang) {
    locale.value = window.jingrow.boot.lang
  } else {
    const saved = localStorage.getItem('locale')
    if (saved) {
      locale.value = saved
    }
  }
}

export function getAllTranslations(): Record<string, string> {
  if (typeof window !== 'undefined' && window.jingrow?._messages) {
    return window.jingrow._messages
  }
  return {}
}

export function isTranslationsLoaded(): boolean {
  return !!(typeof window !== 'undefined' && window.jingrow?._messages)
}

export async function loadTranslationsFromBackend(): Promise<void> {
  const isAuthenticated = document.cookie.includes('sid=') || 
                         document.cookie.includes('user_id=') ||
                         localStorage.getItem('jingrow_authenticated') === 'true'
  
  if (!isAuthenticated) {
    return
  }

  try {
    const response = await fetch('/api/action/jingrow.sessions.get_translations', {
      method: 'POST',
      credentials: 'include',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })

    if (!response.ok) {
      return
    }

    const result = await response.json()
    
    if (result.message) {
      const data = result.message
      
      if (!window.jingrow) {
        (window as any).jingrow = {}
      }
      
      if (data.messages) {
        window.jingrow._messages = data.messages
      }
      
      if (data.lang) {
        locale.value = data.lang
      }
      
    }
    
  } catch (error) {
  }
}