<script setup lang="ts">
const { t } = useI18n()

interface Country {
  name: {
    common: string
    official: string
  }
}

const { data: countries, pending, refresh } = await useFetch<Country[]>(
  'https://restcountries.com/v3.1/all?fields=name',
  {
    cache: 'no-store',
    default: () => [] as Country[]
  }
)

const sortedCountries = computed(() => {
  return [...(countries.value || [])].sort((a, b) =>
    a.name.common.localeCompare(b.name.common)
  )
})

const refreshCountries = () => {
  console.log('refresh')
  refresh()
}
onMounted(() => {
  console.log('onMounted')
  refresh()
})
</script>

<template>
  <!-- extendeddashboard is a custom layout defined in the extended example -->
  <NuxtLayout
    :page-title="t('dashboard.title')"
    :name="'extendeddashboard' as any"
    type="dashboard"
  >
    <template #actions>
      <UButton
        :icon="useSolarIcon('refresh-square')"
        variant="soft"
        color="primary"
        size="sm"
        :loading="pending"
        @click="refreshCountries"
      >
        {{ t('dashboard.customReload') }}
      </UButton>
    </template>
    <UPageBody>
      <PageMainCard
        :title="t('dashboard.countriesTitle')"
        :description="t('dashboard.countriesDescription')"
        :icon="useSolarIcon('global')"
        :loading="pending"
        @refresh="refreshCountries"
      >
        <div
          class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2 max-h-96 overflow-y-auto"
        >
          <template v-if="!pending && countries?.length">
            <div
              v-for="country in sortedCountries"
              :key="country.name.common"
              class="p-2 rounded-md bg-neutral-50 dark:bg-neutral-800 text-sm truncate"
              :title="country.name.official"
            >
              {{ country.name.common }}
            </div>
          </template>
          <template v-else>
            <USkeleton
              v-for="i in 46"
              :key="i"
              class="p-2 rounded-md text-sm h-8"
            />
          </template>
        </div>
        <template #footer-actions>
          <span class="text-sm text-muted">
            {{ pending ? 'Loading...' : t('dashboard.countriesCount', { count: countries?.length || 0 }) }}
          </span>
        </template>
      </PageMainCard>
    </UPageBody>
  </NuxtLayout>
</template>
