<template>
  <LayoutContainer>
    <v-card>
      <v-row>
        <v-col cols="12" md="4" class="d-flex justify-center">
          <v-img src="/images/logos/Logo-HelloAsso.svg" class="logo" />
        </v-col>

        <v-col cols="12" md="8" class="presentation">
          {{ $t('helloasso_presentation') }}
        </v-col>
      </v-row>

      <v-row>
        <v-col cols="12" class="d-flex justify-center align-center w-100 mt-6">
          <UiButtonHelloAssoConnect
            v-if="!helloAssoProfile || !helloAssoProfile.token"
            @click="onHelloAssoConnectClicked"
          />

          <div v-else>
            <v-row>
              <v-icon icon="fas fa-check" color="success" class="mr-3" />
              {{ $t('your_helloasso_account_is_linked') }}
            </v-row>
            <v-row>
              Token : {{ helloAssoProfile.token.slice(0, 30) }}...
            </v-row>
          </div>
        </v-col>
      </v-row>
    </v-card>
  </LayoutContainer>
</template>

<script setup lang="ts">
import AuthUrl from '~/models/ApiResources/HelloAsso/AuthUrl'
import HelloAssoProfile from '~/models/ApiResources/HelloAsso/HelloAssoProfile'
import { useEntityManager } from '~/composables/data/useEntityManager'
import { useEntityFetch } from '~/composables/data/useEntityFetch'

const { em } = useEntityManager()

const onHelloAssoConnectClicked = async () => {
  // Important de régénérer une URL avec un nouveau challenge à chaque
  // essai (entre autres pour supporter le HMR pendant les tests en local,
  // ou en cas d'erreur et de ré-essai)
  const authUrl = await em.fetch(AuthUrl)

  navigateTo(authUrl.authUrl, {
    external: true,
    open: {
      target: '_blank',
      windowFeatures: {
        popup: true,
        width: 900,
        height: 600,
      },
    },
  })
}

onMounted(() => {
  window.addEventListener('message', (event) => {
    if (event.origin !== window.location.origin) {
      return
    }
    if (!event.data || !event.data.code) {
      return
    }
    onHelloAssoConnected()
  })
})

const { fetch } = useEntityFetch()

const { data: helloAssoProfile, refresh: refreshHelloAsso } = await fetch(HelloAssoProfile)

const onHelloAssoConnected = async () => {
  console.log('Helloasso connected')
  await refreshHelloAsso()
}

</script>

<style scoped lang="scss">
.v-card {
  padding: 48px;
  max-width: 70%;
  margin: 36px auto;

  @media (max-width: 600px) {
    max-width: 90%;
  }
}

.logo {
  max-width: 80%;
}

.presentation {
  border-left: 3px solid rgb(var(--v-theme-info));
  padding: 0 24px;
  color: rgb(var(--v-theme-on-neutral));
}

.authDialog {
  max-width: 90%;
}
</style>
