<script setup lang="ts">
import type { LanguageSwitcherProps } from '../types'

const { locale, setLocale } = useI18n()
const { loggedIn } = useAuth()
const { apiCall } = useApiClient()

withDefaults(defineProps<LanguageSwitcherProps>(), {
  small: false
})

const items = [
  [{
    label: 'Nederlands',
    icon: 'i-circle-flags-nl',
    onSelect: () => switchLanguage('nl')
  }, {
    label: 'English',
    icon: 'i-circle-flags-en',
    onSelect: () => switchLanguage('en')
  }]
]

async function switchLanguage(langCode: 'en' | 'nl') {
  // Switch the locale
  await setLocale(langCode as 'en' | 'nl')

  // If user is logged in, persist to profile
  if (loggedIn.value) {
    const response = await apiCall('/api/user/preferences', {
      method: 'PATCH',
      body: { preferredLanguage: langCode }
    })
    if (!response.success) {
      // Don't show error to user - locale switch already happened
      console.error('[LanguageSwitcher] Failed to save language preference:', response.error)
    }
  }
}
</script>

<template>
  <div class="inline-flex relative">
    <UDropdownMenu :items="items">
      <UButton
        variant="outline"
        :label="locale.toUpperCase()"
      />
    </UDropdownMenu>
  </div>
</template>
