/**
 * Load translations from JSON files
 */

export type SupportedLanguage = 'en' | 'fr' | 'es' | 'de' | 'fa' | 'it' | 'pt' | 'ru' | 'zh' | 'ja' | 'ko' | 'ar' | 'hi' | 'nl' | 'pl'

export interface Translations {
  auth: {
    signIn: string
    signUp: string
    email: string
    password: string
    name: string
    emailPlaceholder: string
    passwordPlaceholder: string
    namePlaceholder: string
    passwordMinChars: string
    resetPassword: string
    resetPasswordInstructions: string
    forgotPassword: string
    noAccount: string
    hasAccount: string
    signInToAccount: string
    createAccount: string
    rememberMe: string
    orContinueWith: string
    checkYourEmail: string
    resetEmailSent: string
    returnToLogin: string
    forgotPasswordTitle: string
    forgotPasswordDescription: string
    sending: string
    sendResetLink: string
    backToLogin: string
    signOut: string
  }
  sidebar: {
    notes: string
    reminders: string
    labels: string
    editLabels: string
    archive: string
    trash: string
    newNoteTabs: string
    newNoteTabsHint: string
  }
  notes: {
    title: string
    newNote: string
    untitled: string
    placeholder: string
    markdownPlaceholder: string
    titlePlaceholder: string
    listItem: string
    addListItem: string
    newChecklist: string
    add: string
    adding: string
    close: string
    confirmDelete: string
    confirmLeaveShare: string
    sharedBy: string
    leaveShare: string
    delete: string
    archive: string
    unarchive: string
    pin: string
    unpin: string
    color: string
    changeColor: string
    setReminder: string
    setReminderButton: string
    date: string
    time: string
    reminderDateTimeRequired: string
    invalidDateTime: string
    reminderMustBeFuture: string
    reminderSet: string
    reminderPastError: string
    reminderRemoved: string
    addImage: string
    addLink: string
    linkAdded: string
    linkMetadataFailed: string
    linkAddFailed: string
    invalidFileType: string
    fileTooLarge: string
    uploadFailed: string
    contentOrMediaRequired: string
    itemOrMediaRequired: string
    noteCreated: string
    noteCreateFailed: string
    aiAssistant: string
    changeSize: string
    backgroundOptions: string
    moreOptions: string
    remindMe: string
    markdownMode: string
    addCollaborators: string
    duplicate: string
    share: string
    showCollaborators: string
    pinned: string
    others: string
    noNotes: string
    noNotesFound: string
    createFirstNote: string
    emptyStateTabs: string
    size: string
    small: string
    medium: string
    large: string
    shareWithCollaborators: string
    view: string
    edit: string
    readOnly: string
    preview: string
    noContent: string
    takeNote: string
    takeNoteMarkdown: string
    addItem: string
    sharedReadOnly: string
    makeCopy: string
    saving: string
    copySuccess: string
    copyFailed: string
    copy: string
    markdownOn: string
    markdownOff: string
    undo: string
    redo: string
    viewCards: string
    viewTabs: string
    viewCardsTooltip: string
    viewTabsTooltip: string
    viewModeGroup: string
    reorderTabs: string
  }
  pagination: {
    previous: string
    pageInfo: string
    next: string
  }
  labels: {
    title: string
    filter: string
    manage: string
    manageTooltip: string
    changeColor: string
    changeColorTooltip: string
    delete: string
    deleteTooltip: string
    confirmDelete: string
    newLabelPlaceholder: string
    namePlaceholder: string
    addLabel: string
    createLabel: string
    labelName: string
    labelColor: string
    manageLabels: string
    manageLabelsDescription: string
    selectedLabels: string
    allLabels: string
    clearAll: string
    filterByLabel: string
    tagAdded: string
    showLess: string
    showMore: string
    editLabels: string
    editLabelsDescription: string
    noLabelsFound: string
    loading: string
    notebookRequired: string
  }
  search: {
    placeholder: string
    searchPlaceholder: string
    semanticInProgress: string
    semanticTooltip: string
    searching: string
    noResults: string
    resultsFound: string
    exactMatch: string
    related: string
  }
  collaboration: {
    emailPlaceholder: string
    addCollaborator: string
    removeCollaborator: string
    owner: string
    canEdit: string
    canView: string
    shareNote: string
    shareWithCollaborators: string
    addCollaboratorDescription: string
    viewerDescription: string
    emailAddress: string
    enterEmailAddress: string
    invite: string
    peopleWithAccess: string
    noCollaborators: string
    noCollaboratorsViewer: string
    pendingInvite: string
    pending: string
    remove: string
    unnamedUser: string
    done: string
    willBeAdded: string
    alreadyInList: string
    nowHasAccess: string
    accessRevoked: string
    errorLoading: string
    failedToAdd: string
    failedToRemove: string
  }
  ai: {
    analyzing: string
    clickToAddTag: string
    ignoreSuggestion: string
    generatingTitles: string
    generateTitlesTooltip: string
    poweredByAI: string
    languageDetected: string
    processing: string
    tagAdded: string
    titleGenerating: string
    titleGenerateWithAI: string
    titleGenerationMinWords: string
    titleGenerationError: string
    titlesGenerated: string
    titleGenerationFailed: string
    titleApplied: string
    reformulationNoText: string
    reformulationSelectionTooShort: string
    reformulationMinWords: string
    reformulationMaxWords: string
    reformulationError: string
    reformulationFailed: string
    reformulationApplied: string
    transformMarkdown: string
    transforming: string
    transformSuccess: string
    transformError: string
    assistant: string
    generating: string
    generateTitles: string
    reformulateText: string
    reformulating: string
    clarify: string
    shorten: string
    improveStyle: string
    reformulationComparison: string
    original: string
    reformulated: string
  }
  batchOrganization: {
    error: string
    noNotesSelected: string
    title: string
    description: string
    analyzing: string
    notesToOrganize: string
    selected: string
    noNotebooks: string
    noSuggestions: string
    confidence: string
    unorganized: string
    applying: string
    apply: string
  }
  autoLabels: {
    error: string
    noLabelsSelected: string
    created: string
    analyzing: string
    title: string
    description: string
    note: string
    notes: string
    typeContent: string
    createNewLabel: string
    new: string
  }
  titleSuggestions: {
    available: string
    title: string
    generating: string
    selectTitle: string
    dismiss: string
  }
  semanticSearch: {
    exactMatch: string
    related: string
    searching: string
  }
  paragraphRefactor: {
    title: string
    shorten: string
    expand: string
    improve: string
    formal: string
    casual: string
  }
  memoryEcho: {
    title: string
    description: string
    dailyInsight: string
    insightReady: string
    viewConnection: string
    helpful: string
    notHelpful: string
    dismiss: string
    thanksFeedback: string
    thanksFeedbackImproving: string
    connections: string
    connection: string
    connectionsBadge: string
    fused: string
    overlay: {
      title: string
      searchPlaceholder: string
      sortBy: string
      sortSimilarity: string
      sortRecent: string
      sortOldest: string
      viewAll: string
      loading: string
      noConnections: string
    }
    comparison: {
      title: string
      similarityInfo: string
      highSimilarityInsight: string
      untitled: string
      clickToView: string
      helpfulQuestion: string
      helpful: string
      notHelpful: string
    }
    editorSection: {
      title: string
      loading: string
      view: string
      compare: string
      merge: string
      compareAll: string
      mergeAll: string
    }
    fusion: {
      title: string
      mergeNotes: string
      notesToMerge: string
      optionalPrompt: string
      promptPlaceholder: string
      generateFusion: string
      generating: string
      previewTitle: string
      edit: string
      modify: string
      finishEditing: string
      optionsTitle: string
      archiveOriginals: string
      keepAllTags: string
      useLatestTitle: string
      createBacklinks: string
      cancel: string
      confirmFusion: string
      success: string
      error: string
      generateError: string
      noContentReturned: string
      unknownDate: string
    }
  }
  nav: {
    home: string
    notes: string
    notebooks: string
    generalNotes: string
    archive: string
    settings: string
    profile: string
    aiSettings: string
    logout: string
    login: string
    adminDashboard: string
    diagnostics: string
    trash: string
    support: string
    reminders: string
    userManagement: string
    accountSettings: string
    manageAISettings: string
    configureAI: string
    supportDevelopment: string
    supportDescription: string
    buyMeACoffee: string
    donationDescription: string
    donateOnKofi: string
    donationNote: string
    sponsorOnGithub: string
    sponsorDescription: string
    workspace: string
    quickAccess: string
    myLibrary: string
    favorites: string
    recent: string
    proPlan: string
  }
  settings: {
    title: string
    description: string
    account: string
    appearance: string
    theme: string
    themeLight: string
    themeDark: string
    themeSystem: string
    notifications: string
    language: string
    selectLanguage: string
    privacy: string
    security: string
    about: string
    version: string
    settingsSaved: string
    settingsError: string
  }
  profile: {
    title: string
    description: string
    displayName: string
    email: string
    changePassword: string
    changePasswordDescription: string
    currentPassword: string
    newPassword: string
    confirmPassword: string
    updatePassword: string
    passwordChangeSuccess: string
    passwordChangeFailed: string
    passwordUpdated: string
    passwordError: string
    languagePreferences: string
    languagePreferencesDescription: string
    preferredLanguage: string
    selectLanguage: string
    languageDescription: string
    autoDetect: string
    updateSuccess: string
    updateFailed: string
    languageUpdateSuccess: string
    languageUpdateFailed: string
    profileUpdated: string
    profileError: string
    accountSettings: string
    manageAISettings: string
    displaySettings: string
    displaySettingsDescription: string
    fontSize: string
    selectFontSize: string
    fontSizeSmall: string
    fontSizeMedium: string
    fontSizeLarge: string
    fontSizeExtraLarge: string
    fontSizeDescription: string
    fontSizeUpdateSuccess: string
    fontSizeUpdateFailed: string
    showRecentNotes: string
    showRecentNotesDescription: string
    recentNotesUpdateSuccess: string
    recentNotesUpdateFailed: string
  }
  aiSettings: {
    title: string
    description: string
    features: string
    provider: string
    providerAuto: string
    providerOllama: string
    providerOpenAI: string
    frequency: string
    frequencyDaily: string
    frequencyWeekly: string
    saving: string
    saved: string
    error: string
  }
  general: {
    loading: string
    save: string
    cancel: string
    add: string
    edit: string
    confirm: string
    close: string
    back: string
    next: string
    previous: string
    submit: string
    reset: string
    apply: string
    clear: string
    select: string
    tryAgain: string
    error: string
    operationSuccess: string
    operationFailed: string
  }
  colors: {
    default: string
    red: string
    blue: string
    green: string
    yellow: string
    purple: string
    pink: string
    orange: string
    gray: string
  }
  reminder: {
    title: string
    setReminder: string
    removeReminder: string
    reminderDate: string
    reminderTime: string
    save: string
    cancel: string
  }
  notebook: {
    create: string
    createNew: string
    createDescription: string
    name: string
    selectIcon: string
    selectColor: string
    cancel: string
    creating: string
    edit: string
    editDescription: string
    delete: string
    deleteWarning: string
    deleteConfirm: string
    summary: string
    summaryDescription: string
    generating: string
    summaryError: string
  }
  notebookSuggestion: {
    title: string
    description: string
    move: string
    dismiss: string
    dismissIn: string
    moveToNotebook: string
    generalNotes: string
  }
  admin: {
    title: string
    userManagement: string
    aiTesting: string
    settings: string
    security: {
      title: string
      description: string
      allowPublicRegistration: string
      allowPublicRegistrationDescription: string
      updateSuccess: string
      updateFailed: string
    }
    ai: {
      title: string
      description: string
      tagsGenerationProvider: string
      tagsGenerationDescription: string
      embeddingsProvider: string
      embeddingsDescription: string
      provider: string
      baseUrl: string
      model: string
      apiKey: string
      selectOllamaModel: string
      openAIKeyDescription: string
      modelRecommendations: string
      commonModelsDescription: string
      selectEmbeddingModel: string
      commonEmbeddingModels: string
      saving: string
      saveSettings: string
      openTestPanel: string
      updateSuccess: string
      updateFailed: string
      providerTagsRequired: string
      providerEmbeddingRequired: string
    }
    smtp: {
      title: string
      description: string
      host: string
      port: string
      username: string
      password: string
      fromEmail: string
      forceSSL: string
      ignoreCertErrors: string
      saveSettings: string
      sending: string
      testEmail: string
      updateSuccess: string
      updateFailed: string
      testSuccess: string
      testFailed: string
    }
    users: {
      createUser: string
      addUser: string
      createUserDescription: string
      name: string
      email: string
      password: string
      role: string
      createSuccess: string
      createFailed: string
      deleteSuccess: string
      deleteFailed: string
      roleUpdateSuccess: string
      roleUpdateFailed: string
      table: {
        name: string
        email: string
        role: string
        createdAt: string
        actions: string
      }
    }
    aiTest: {
      title: string
      description: string
      tagsTestTitle: string
      tagsTestDescription: string
      embeddingsTestTitle: string
      embeddingsTestDescription: string
      howItWorksTitle: string
      provider: string
      model: string
      testing: string
      runTest: string
      testPassed: string
      testFailed: string
      responseTime: string
      generatedTags: string
      embeddingDimensions: string
      vectorDimensions: string
      first5Values: string
      error: string
      testError: string
      tipTitle: string
      tipDescription: string
    }
  }
  about: {
    title: string
    description: string
    appName: string
    appDescription: string
    version: string
    buildDate: string
    platform: string
    platformWeb: string
    features: {
      title: string
      description: string
      titleSuggestions: string
      semanticSearch: string
      paragraphReformulation: string
      memoryEcho: string
      notebookOrganization: string
      dragDrop: string
      labelSystem: string
      multipleProviders: string
    }
    technology: {
      title: string
      description: string
      frontend: string
      backend: string
      database: string
      authentication: string
      ai: string
      ui: string
      testing: string
    }
    support: {
      title: string
      description: string
      documentation: string
      reportIssues: string
      feedback: string
    }
  }
  support: {
    title: string
    description: string
    buyMeACoffee: string
    donationDescription: string
    donateOnKofi: string
    kofiDescription: string
    sponsorOnGithub: string
    sponsorDescription: string
    githubDescription: string
    howSupportHelps: string
    directImpact: string
    sponsorPerks: string
    transparency: string
    transparencyDescription: string
    hostingServers: string
    domainSSL: string
    aiApiCosts: string
    totalExpenses: string
    otherWaysTitle: string
    starGithub: string
    reportBug: string
    contributeCode: string
    shareTwitter: string
  }
  demoMode: {
    title: string
    activated: string
    deactivated: string
    toggleFailed: string
    description: string
    parametersActive: string
    similarityThreshold: string
    delayBetweenNotes: string
    unlimitedInsights: string
    createNotesTip: string
  }
  resetPassword: {
    title: string
    description: string
    invalidLinkTitle: string
    invalidLinkDescription: string
    requestNewLink: string
    newPassword: string
    confirmNewPassword: string
    resetting: string
    resetPassword: string
    passwordMismatch: string
    success: string
    loading: string
  }
  dataManagement: {
    title: string
    toolsDescription: string
    export: {
      title: string
      description: string
      button: string
      success: string
      failed: string
    }
    import: {
      title: string
      description: string
      button: string
      success: string
      failed: string
    }
    delete: {
      title: string
      description: string
      button: string
      confirm: string
      success: string
      failed: string
    }
    indexing: {
      title: string
      description: string
      button: string
      success: string
      failed: string
    }
    cleanup: {
      title: string
      description: string
      button: string
      failed: string
    }
  }
  appearance: {
    title: string
    description: string
    notesViewDescription: string
    notesViewLabel: string
    notesViewTabs: string
    notesViewMasonry: string
  }
  generalSettings: {
    title: string
    description: string
  }
  toast: {
    saved: string
    saveFailed: string
    operationSuccess: string
    operationFailed: string
    openingConnection: string
    openConnectionFailed: string
    thanksFeedback: string
    thanksFeedbackImproving: string
    feedbackFailed: string
    notesFusionSuccess: string
  }
  testPages: {
    titleSuggestions: {
      title: string
      contentLabel: string
      placeholder: string
      wordCount: string
      status: string
      analyzing: string
      idle: string
      error: string
      suggestions: string
      noSuggestions: string
    }
  }
  trash: {
    title: string
    empty: string
    restore: string
    deletePermanently: string
  }
  footer: {
    privacy: string
    terms: string
    openSource: string
  }
  connection: {
    similarityInfo: string
    clickToView: string
    isHelpful: string
    helpful: string
    notHelpful: string
    memoryEchoDiscovery: string
  }
  diagnostics: {
    title: string
    configuredProvider: string
    apiStatus: string
    testDetails: string
    troubleshootingTitle: string
    tip1: string
    tip2: string
    tip3: string
    tip4: string
  }
  batch: {
    organizeWithAI: string
    organize: string
  }
  common: {
    unknown: string
    notAvailable: string
    loading: string
    error: string
    success: string
    confirm: string
    cancel: string
    close: string
    save: string
    delete: string
    edit: string
    add: string
    remove: string
    search: string
    noResults: string
    required: string
    optional: string
  }
  time: {
    justNow: string
    minutesAgo: string
    hoursAgo: string
    daysAgo: string
    yesterday: string
    today: string
    tomorrow: string
  }
  favorites: {
    title: string
    toggleSection: string
    noFavorites: string
    pinToFavorite: string
  }
  notebooks: {
    create: string
    allNotebooks: string
    noNotebooks: string
    createFirst: string
  }
  ui: {
    close: string
    open: string
    expand: string
    collapse: string
  }
  [key: string]: any
}

/**
 * Load translations from JSON files
 */
export async function loadTranslations(language: SupportedLanguage): Promise<Translations> {
  try {
    const translations = await import(`@/locales/${language}.json`)
    return translations.default as unknown as Translations
  } catch (error) {
    console.error(`Failed to load translations for ${language}:`, error)
    const enTranslations = await import(`@/locales/en.json`)
    return enTranslations.default as unknown as Translations
  }
}

/**
 * Get nested translation value from object using dot notation
 */
export function getTranslationValue(translations: Translations, key: string): string {
  const keys = key.split('.')
  let value: any = translations

  for (const k of keys) {
    value = value?.[k]
  }

  return typeof value === 'string' ? value : key
}
