<!--
  LoginPage — passwordless portal login via magic link.

  The only entry point for customers who don't have a ?token= in their URL.
  Takes an email or phone, asks the hub to send a 24h magic link via SMS +
  email, then shows a success state with redacted destinations so the user
  knows where to look.

  Failure modes surfaced to the user:
  - Empty input → inline field error
  - Rate limit (429) → banner with retry countdown
  - Network error → toast
  - No match → still shown as success (anti-enumeration). If sent array is
    empty, we say "Lien envoyé" but no destinations — matches the hub's
    behaviour. This is intentional; legitimate users who typo their address
    will see "no channels" and retry with the right one.

  See docs/features/billing-payments.md for the full Stripe + magic-link
  flow this page plugs into.
-->
<template>
  <q-page class="flex flex-center" padding>
    <div class="login-card">
      <div class="text-center q-mb-lg">
        <img src="https://store.targo.ca/clients/images/logo_trans_noir.png"
          alt="Gigafibre" style="max-width: 180px" />
        <div class="text-h5 text-weight-bold q-mt-md">Portail client</div>
        <div class="text-body2 text-grey-7 q-mt-xs">
          Entrez votre courriel ou téléphone pour recevoir un lien d'accès
        </div>
      </div>

      <!-- Before send -->
      <div v-if="!sent">
        <q-input
          v-model="identifier"
          outlined
          label="Courriel ou téléphone"
          autofocus
          :error="!!errorMsg"
          :error-message="errorMsg"
          :disable="loading"
          @keyup.enter="submit"
        >
          <template #prepend>
            <q-icon :name="isEmail ? 'email' : 'phone'" />
          </template>
        </q-input>

        <q-btn
          class="full-width q-mt-md"
          color="primary"
          unelevated
          size="lg"
          label="Recevoir mon lien"
          icon="send"
          :loading="loading"
          :disable="!identifier.trim()"
          @click="submit"
        />

        <div class="text-caption text-grey-6 q-mt-md text-center">
          Lien valide 24&nbsp;h. Pas de mot de passe requis.
        </div>
      </div>

      <!-- After send -->
      <div v-else class="text-center">
        <q-icon name="mark_email_read" color="positive" size="64px" />
        <div class="text-h6 q-mt-md">Lien envoyé&nbsp;!</div>
        <div v-if="redacted.length" class="text-body2 text-grey-7 q-mt-sm">
          Vérifiez&nbsp;:
          <div class="q-mt-xs">
            <span v-for="(r, i) in redacted" :key="i" class="q-mr-sm">
              <q-chip dense outline color="grey-7" :label="r" />
            </span>
          </div>
        </div>
        <div v-else class="text-body2 text-grey-7 q-mt-sm">
          Si votre compte existe, un lien vous a été envoyé.
          Vérifiez vos SMS et courriels.
        </div>
        <q-btn
          flat color="primary" class="q-mt-lg" label="Envoyer à nouveau"
          icon="replay" @click="sent = false" no-caps
        />
      </div>

      <!-- Rate-limit banner -->
      <q-banner v-if="rateLimited" rounded dense class="bg-orange-1 q-mt-md">
        <template #avatar>
          <q-icon name="schedule" color="warning" />
        </template>
        <div class="text-body2">{{ rateLimitMsg }}</div>
      </q-banner>
    </div>
  </q-page>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useQuasar } from 'quasar'
import { requestPortalLink } from 'src/api/auth-portal'

const $q = useQuasar()

const identifier = ref('')
const loading = ref(false)
const sent = ref(false)
const redacted = ref([])
const errorMsg = ref('')
const rateLimited = ref(false)
const rateLimitMsg = ref('')

const isEmail = computed(() => identifier.value.includes('@'))

async function submit () {
  const raw = identifier.value.trim()
  if (!raw) {
    errorMsg.value = 'Entrez un courriel ou un numéro de téléphone'
    return
  }
  errorMsg.value = ''
  rateLimited.value = false
  loading.value = true
  try {
    const r = await requestPortalLink(raw)
    redacted.value = r.redacted || []
    sent.value = true
  } catch (e) {
    if (e.code === 'rate_limit') {
      rateLimited.value = true
      rateLimitMsg.value = e.message
    } else {
      $q.notify({
        type: 'negative',
        message: 'Erreur réseau. Réessayez dans un moment.',
        timeout: 4000,
      })
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-card {
  background: #fff;
  border-radius: 12px;
  padding: 32px;
  max-width: 440px;
  width: 100%;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
}
</style>
