<template>
  <Section variant="plain" paddingY="md">
    <Stack gap="6">
      <PageHeader
        :title="t('profileAddresses.header.title')"
        :actions="[{ label: t('profileAddresses.actions.add'), icon: 'lucide:plus', to: localePath('/clientarea/addresses/new') }]"
      />

    <!-- Addresses list -->
    <Card v-if="isLoading" padding="lg">
      <Stack align="center" gap="3">
        <Spinner />
        <Text tone="muted">{{ t('profileAddresses.states.loading') }}</Text>
      </Stack>
    </Card>

    <Grid v-else-if="addresses.length" :cols="1" :md="2" :gap="4">
      <Card v-for="addr in addresses" :key="addr.uuid" padding="small" interactive>
        <div class="flex flex-col gap-1">
          <!-- Header: name + dropdown -->
          <div class="flex items-center justify-between">
            <Text size="base" weight="semibold" class="truncate">{{ addr.name }}</Text>
            <div class="dropdown dropdown-end">
              <label tabindex="0" class="btn btn-ghost btn-xs btn-circle">
                <Icon name="lucide:more-vertical" size="16" />
              </label>
              <ul tabindex="0" class="dropdown-content z-10 menu p-2 shadow bg-base-100 rounded-box w-40">
                <li>
                  <a class="text-error" @click="deleteAddress(addr.uuid)">
                    <Icon name="lucide:trash-2" size="16" />
                    {{ t('profileAddresses.actions.delete') }}
                  </a>
                </li>
              </ul>
            </div>
          </div>

          <!-- Address text -->
          <Text tone="muted" size="sm" class="line-clamp-2">{{ addr.address }}</Text>

          <!-- Footer: country flag -->
          <div class="flex items-center justify-between mt-1">
            <span class="text-lg">{{ isoToEmoji(addr.countryCode) }}</span>
          </div>
        </div>
      </Card>
    </Grid>

    <EmptyState
      v-else
      icon="📍"
      :title="t('profileAddresses.empty.title')"
      :description="t('profileAddresses.empty.description')"
      :action-label="t('profileAddresses.empty.cta')"
      :action-to="localePath('/clientarea/addresses/new')"
      action-icon="lucide:plus"
    />
    </Stack>
  </Section>
</template>

<script setup lang="ts">
definePageMeta({
  middleware: ['auth-oidc']
})

const { execute, mutate } = useGraphQL()
const { t } = useI18n()
const localePath = useLocalePath()

const addresses = ref<any[]>([])
const isLoading = ref(true)

// ISO code to emoji flag
const isoToEmoji = (code: string | null | undefined): string => {
  if (!code) return '🌍'
  return code.toUpperCase().split('').map(char => String.fromCodePoint(0x1F1E6 - 65 + char.charCodeAt(0))).join('')
}

const loadAddresses = async () => {
  isLoading.value = true
  try {
    const { GetTeamAddressesDocument } = await import('~/composables/graphql/team/teams-generated')
    const { data, error: addressesError } = await useServerQuery('addresses-list', GetTeamAddressesDocument, {}, 'team', 'teams')
    if (addressesError.value) throw addressesError.value
    addresses.value = data.value?.teamAddresses || []
  } catch (e) {
    console.error('Failed to load addresses', e)
  } finally {
    isLoading.value = false
  }
}

const deleteAddress = async (uuid: string) => {
  if (!confirm(t('profileAddresses.actions.confirm_delete'))) return

  try {
    const { DeleteTeamAddressDocument } = await import('~/composables/graphql/team/teams-generated')
    const result = await mutate(DeleteTeamAddressDocument, { uuid }, 'team', 'teams')

    if (result.deleteTeamAddress?.success) {
      await loadAddresses()
    }
  } catch (e) {
    console.error('Failed to delete address', e)
  }
}

await loadAddresses()
</script>
