<script setup>
import { ref } from 'vue'
import { Inertia } from '@inertiajs/inertia'
import { usePage } from '@inertiajs/inertia-vue3'
import Dropdown from './DropdownMenu.vue'

// variables
const currentLocale = ref(usePage().props.value.currentLocale)

// methods
const isCurrent = (language) => {
  return language.iso_code === currentLocale.value.iso_code
}

const changeLocale = (language) => {
  if (language.iso_code !== currentLocale.value.iso_code) {
    Inertia.post(route('locale.set'), language, {
      replace: true,
      onSuccess: page => {
        currentLocale.value = page.props.currentLocale
      },
      onError: errors => {
console.log(errors)
      }
    })
  }
}
</script>

<template>
   <Dropdown align="right" width="60">
      <template #trigger>
          <div class="py-2 px-4 inline-grid grid-flow-col auto-cols-max gap-x-2 items-center bg-white hover:bg-gray-50 text-sm leading-4 font-medium rounded-md cursor-pointer">
              <svg class="h-4 w-8">
                  <use :href="`#flag-${currentLocale.iso_code}`"></use>
              </svg>
              <span class="ml-2">{{ currentLocale.localized_name }}</span>
          </div>
      </template>

      <template #content>
          <div class="w-60">
              <button type="button" v-for="(lang, langIdx) in $page.props.availableLocales" :key="langIdx" @click="changeLocale(lang)" class="py-2 px-4 inline-grid grid-flow-col auto-cols-max gap-x-2 items-center w-full" :class="{ 'text-white bg-sky-600 cursor-default': isCurrent(lang), 'hover:bg-sky-600/50': !isCurrent(lang) }">
                  <svg class="h-4 w-8">
                      <use :href="`#flag-${lang.iso_code}`"></use>
                  </svg>
                  <span class="ml-2">{{ lang.localized_name }}</span>
              </button>
          </div>
      </template>
   </Dropdown>
</template>
