<template>
  <!-- Carte-cadeau / récompense : voir/copier le lien (msg.gigafibre.ca/g/<token>), personnaliser (composeur) ou envoyer.
       Réutilise le pool de récompenses. Extrait de ClientDetailPage (découpage 2026-06-30). -->
  <q-dialog :model-value="modelValue" @update:model-value="v => emit('update:modelValue', v)">
    <q-card style="min-width:340px;max-width:520px">
      <q-card-section class="row items-center q-pb-none">
        <q-icon name="card_giftcard" color="warning" size="22px" class="q-mr-sm" />
        <div class="text-h6">Carte-cadeau</div>
        <q-space />
        <q-btn flat round dense icon="close" v-close-popup />
      </q-card-section>
      <q-card-section>
        <div class="text-caption text-grey-7 q-mb-sm">{{ reward.customerName }}<span v-if="reward.email"> · {{ reward.email }}</span></div>
        <q-inner-loading :showing="reward.loading" />
        <div v-if="reward.existing.length" class="q-mb-md">
          <div class="text-subtitle2 q-mb-xs">Récompenses de ce client</div>
          <div v-for="(r, i) in reward.existing" :key="i" class="q-mb-sm">
            <div class="row items-center q-gutter-xs">
              <q-chip dense :color="rewardStatusColor(r.status)" text-color="white" class="q-ma-none">{{ r.status }}</q-chip>
              <span class="text-weight-medium">{{ formatMoney((r.value_cents || 0) / 100) }}</span>
              <span v-if="r.clicks" class="text-caption text-green-7">· ouvert</span>
              <q-space />
              <q-btn v-if="r.is_draft && r.conversation_token" flat dense no-caps size="sm" color="primary" icon="edit" label="Éditer" @click="rewardEditDraft(r)">
                <q-tooltip>Éditer ce brouillon dans l'éditeur de courriel</q-tooltip>
              </q-btn>
              <q-btn flat dense no-caps size="sm" color="primary" icon-right="open_in_new" label="Suivi" :to="{ path: '/campaigns/gifts', query: { q: r.gift_token } }">
                <q-tooltip>Voir cette récompense dans le suivi des campagnes</q-tooltip>
              </q-btn>
              <q-btn v-if="!r.clicked" flat dense round size="sm" color="negative" icon="delete_outline" @click="rewardDelete(r)">
                <q-tooltip>{{ r.is_draft ? 'Supprimer ce brouillon (remet le lien en réserve)' : 'Révoquer — remet le lien en réserve' }}</q-tooltip>
              </q-btn>
            </div>
            <q-input dense outlined readonly :model-value="r.link" class="q-mt-xs" @focus="e => e.target.select()">
              <template #append><q-btn flat dense round icon="content_copy" @click="copyTxt(r.link)" /></template>
            </q-input>
          </div>
        </div>
        <q-banner v-if="!reward.email" dense class="bg-orange-1 text-warning q-mb-sm">Aucun courriel au dossier — copie un lien à partager autrement, ou ajoute un courriel pour l'envoyer.</q-banner>
        <q-banner v-else-if="reward.poolAvailable === 0" dense class="bg-red-1 text-negative q-mb-sm">Réserve de cartes-cadeaux vide (Campagnes → Réserve).</q-banner>
        <div v-else-if="reward.poolAvailable !== null" class="text-caption text-grey-7 q-mb-sm">Nouvelle récompense : <b>{{ formatMoney(reward.value / 100) }}</b> · {{ reward.poolAvailable }} en réserve.</div>
        <div v-if="reward.error" class="text-negative text-caption">{{ reward.error }}</div>
        <div class="q-mt-sm">
          <q-btn flat dense no-caps size="sm" color="primary" icon="campaign" label="Voir le suivi des campagnes" :to="{ path: '/campaigns/gifts', query: { q: reward.email || reward.customerName } }" />
        </div>
      </q-card-section>
      <q-card-actions align="right">
        <q-btn flat no-caps icon="link" label="Copier le lien" :loading="reward.acting === 'link'" :disable="reward.poolAvailable === 0 || reward.loading" @click="rewardCopyLink" />
        <q-btn flat no-caps color="primary" icon="edit" label="Personnaliser" :loading="reward.acting === 'editor'" :disable="!reward.email || reward.poolAvailable === 0 || reward.loading" @click="rewardOpenEditor">
          <q-tooltip>Ouvrir un brouillon dans l'éditeur de courriel pour personnaliser le message</q-tooltip>
        </q-btn>
        <q-btn unelevated no-caps color="warning" text-color="white" icon="send" label="Envoyer" :loading="reward.acting === 'send'" :disable="!reward.email || reward.poolAvailable === 0 || reward.loading" @click="rewardSendEmail">
          <q-tooltip>Envoyer la carte-cadeau directement (sans édition)</q-tooltip>
        </q-btn>
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { reactive, watch } from 'vue'
import { useQuasar } from 'quasar'
import { useRouter } from 'vue-router'
import { formatMoney } from 'src/composables/useFormatters'
import { useConversations } from 'src/composables/useConversations'
import { rewardSend, rewardByCustomer, revokeRewardByToken } from 'src/api/campaigns'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  customer: { type: Object, default: null },
})
const emit = defineEmits(['update:modelValue'])
const $q = useQuasar()
const router = useRouter()
const { openComposeDraft } = useConversations()

const reward = reactive({ loading: false, acting: '', customerId: '', customerName: '', email: '', existing: [], value: 0, poolAvailable: null, error: '' })

watch(() => props.modelValue, (v) => { if (v) openReward() })
function close () { emit('update:modelValue', false) }

function rewardStatusColor (s) { return s === 'sent' ? 'green-7' : s === 'draft' ? 'blue-grey-6' : s === 'link' ? 'green-4' : s === 'pending' ? 'amber-8' : 'grey-6' }
function copyTxt (txt) { try { navigator.clipboard.writeText(txt); $q.notify({ type: 'positive', message: 'Lien copié', timeout: 1200 }) } catch (e) { /* */ } }
async function refreshReward () {
  try { const byc = await rewardByCustomer(reward.customerId, reward.email); reward.existing = byc.rewards || [] } catch (e) { /* */ }
  try { const prev = await rewardSend({ customer_id: reward.customerId, channel: 'email', dry_run: true }); if (prev && !prev.error) { reward.poolAvailable = prev.pool_available; reward.value = prev.gift_value_cents || reward.value } } catch (e) { /* */ }
}
async function openReward () {
  const c = props.customer; if (!c) return
  reward.loading = true; reward.error = ''
  reward.customerId = c.name; reward.customerName = c.customer_name || c.name
  reward.email = c.email_id || c.email_billing || ''
  reward.existing = []; reward.poolAvailable = null; reward.value = 0
  try {
    const [byc, prev] = await Promise.all([
      rewardByCustomer(c.name, reward.email).catch(() => ({ rewards: [] })),
      rewardSend({ customer_id: c.name, channel: 'email', dry_run: true }).catch(e => ({ error: e && e.message }))
    ])
    reward.existing = byc.rewards || []
    if (prev && prev.error) reward.error = prev.error
    else if (prev) { reward.value = prev.gift_value_cents || 0; reward.poolAvailable = prev.pool_available }
  } catch (e) { reward.error = e.message } finally { reward.loading = false }
}
function rewardSendEmail () {
  if (!reward.email) return
  $q.dialog({ title: 'Envoyer la carte-cadeau', message: 'Envoyer ' + formatMoney(reward.value / 100) + ' par courriel à ' + reward.email + ' ?', cancel: true, ok: { label: 'Envoyer', color: 'amber-8' } }).onOk(async () => {
    reward.acting = 'send'
    try {
      const r = await rewardSend({ customer_id: reward.customerId, channel: 'email' })
      if (r.error) $q.notify({ type: 'negative', message: r.error })
      else { $q.notify({ type: 'positive', message: 'Récompense envoyée à ' + reward.email }); await refreshReward() }
    } catch (e) { $q.notify({ type: 'negative', message: 'Échec : ' + e.message }) } finally { reward.acting = '' }
  })
}
async function rewardCopyLink () {
  reward.acting = 'link'
  try {
    const r = await rewardSend({ customer_id: reward.customerId, channel: 'email', mode: 'link' })
    if (r.error) $q.notify({ type: 'negative', message: r.error })
    else if (r.client_link) { copyTxt(r.client_link); $q.notify({ type: 'positive', message: 'Lien de récompense copié' }); await refreshReward() }
  } catch (e) { $q.notify({ type: 'negative', message: 'Échec : ' + e.message }) } finally { reward.acting = '' }
}
async function rewardOpenEditor () {
  reward.acting = 'editor'
  try {
    const r = await rewardSend({ customer_id: reward.customerId, channel: 'email', mode: 'link' })
    if (r.error) { $q.notify({ type: 'negative', message: r.error }); return }
    const first = (reward.customerName || '').trim().split(/\s+/)[0] || ''
    const val = formatMoney((r.gift_value_cents || reward.value || 0) / 100)
    const msg = `Bonjour ${first},\n\nNous tenons à vous offrir une récompense de ${val}. Cliquez ici pour la récupérer :\n${r.client_link}\n\nMerci de votre confiance,\nL'équipe Targo`
    close()
    openComposeDraft({ channel: 'email', to: reward.email, subject: 'Votre récompense Targo 🎁', text: msg, customer: reward.customerId, customerName: reward.customerName })
    $q.notify({ type: 'positive', message: 'Récompense prête — personnalise le message puis envoie.' })
  } catch (e) { $q.notify({ type: 'negative', message: 'Échec : ' + e.message }) } finally { reward.acting = '' }
}
function rewardEditDraft (r) {
  if (!r.conversation_token) return
  close()
  router.push('/communications/c/' + r.conversation_token)
}
function rewardDelete (r) {
  $q.dialog({ title: r.is_draft ? 'Supprimer le brouillon' : 'Révoquer la récompense', message: (r.is_draft ? 'Supprimer ce brouillon' : 'Révoquer cette récompense') + ' (' + formatMoney((r.value_cents || 0) / 100) + ') ? Le lien retourne en réserve.', cancel: true, ok: { label: r.is_draft ? 'Supprimer' : 'Révoquer', color: 'negative' } }).onOk(async () => {
    try {
      const res = await revokeRewardByToken(r.gift_token)
      if (res.error) { $q.notify({ type: 'negative', message: res.error }) }
      else { $q.notify({ type: 'positive', message: r.is_draft ? 'Brouillon supprimé' : 'Récompense révoquée' }); await refreshReward() }
    } catch (e) { $q.notify({ type: 'negative', message: 'Échec : ' + e.message }) }
  })
}
</script>
