<script setup lang="ts">
// Global "plan limit reached" modal. Bound to the upgrade-prompt state
// in useBilling, which is populated by the 402 interceptor in useApi.
// Lives in app.vue so any page that fires an API call benefits from it
// without per-page wiring.

const billing = useBilling()
const router = useRouter()
const upgrading = ref<'pro' | 'business' | null>(null)

const reasonText = computed(() => {
  const p = billing.prompt.value
  if (!p) return ''
  if (p.reason === 'events_per_month') {
    return `You've used ${p.used} of ${p.limit} events this month on the ${labelTier(p.tier)} plan.`
  }
  if (p.reason === 'guests_per_event') {
    return `This event already has ${p.used} of ${p.limit} guests allowed on the ${labelTier(p.tier)} plan.`
  }
  return p.error
})

function labelTier(t: string): string {
  return t.charAt(0).toUpperCase() + t.slice(1)
}

async function quickUpgrade(tier: 'pro' | 'business') {
  upgrading.value = tier
  try {
    await billing.startCheckout(tier)
    // startCheckout navigates the page — nothing else to do.
  } catch {
    // Fallback: send the user to the billing page so they see the error
    // in context.
    await router.push('/dashboard/billing')
    billing.dismissUpgradePrompt()
  } finally {
    upgrading.value = null
  }
}

function viewPlans() {
  billing.dismissUpgradePrompt()
  router.push('/dashboard/billing')
}

// Esc closes the modal — keeps interaction symmetrical with all the
// other dialogs across the app.
function onKeydown(e: KeyboardEvent) {
  if (e.key === 'Escape' && billing.prompt.value) {
    billing.dismissUpgradePrompt()
  }
}
if (import.meta.client) {
  onMounted(() => window.addEventListener('keydown', onKeydown))
  onUnmounted(() => window.removeEventListener('keydown', onKeydown))
}
</script>

<template>
  <Teleport to="body">
    <div
      v-if="billing.prompt.value"
      class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm"
      @click.self="billing.dismissUpgradePrompt()"
    >
      <div
        role="alertdialog"
        aria-modal="true"
        aria-labelledby="upgrade-title"
        aria-describedby="upgrade-desc"
        class="w-full max-w-md rounded-lg border border-zinc-800 bg-zinc-900 p-5 shadow-2xl"
      >
        <div class="mb-3 flex items-start gap-3">
          <div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-brand-500/15">
            <svg class="h-4 w-4 text-brand-400" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
              <path fill-rule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clip-rule="evenodd" />
            </svg>
          </div>
          <div class="min-w-0">
            <h3 id="upgrade-title" class="text-base font-semibold text-zinc-100">Plan limit reached</h3>
            <p id="upgrade-desc" class="mt-1 text-sm text-zinc-400">{{ reasonText }}</p>
          </div>
        </div>

        <p class="mb-4 text-sm text-zinc-300">Pick a plan to keep going — your work isn't lost.</p>

        <div class="space-y-2">
          <button
            type="button"
            class="flex w-full items-center justify-between rounded-md border border-brand-700/60 bg-brand-500/10 px-3 py-3 text-left transition hover:bg-brand-500/15 disabled:opacity-50"
            :disabled="upgrading !== null"
            @click="quickUpgrade('pro')"
          >
            <span>
              <span class="block text-sm font-medium text-zinc-100">Upgrade to Pro</span>
              <span class="block text-xs text-zinc-500">$49 / month · 10 events · 1,000 guests per event</span>
            </span>
            <span class="text-xs text-zinc-400">{{ upgrading === 'pro' ? 'Opening checkout…' : '→' }}</span>
          </button>

          <button
            type="button"
            class="flex w-full items-center justify-between rounded-md border border-zinc-700 bg-zinc-950 px-3 py-3 text-left transition hover:border-zinc-500 hover:bg-zinc-900 disabled:opacity-50"
            :disabled="upgrading !== null"
            @click="quickUpgrade('business')"
          >
            <span>
              <span class="block text-sm font-medium text-zinc-100">Upgrade to Business</span>
              <span class="block text-xs text-zinc-500">$199 / month · Unlimited events · 5,000 guests per event</span>
            </span>
            <span class="text-xs text-zinc-400">{{ upgrading === 'business' ? 'Opening checkout…' : '→' }}</span>
          </button>
        </div>

        <div class="mt-4 flex items-center justify-between text-xs">
          <button
            type="button"
            class="text-zinc-400 hover:text-zinc-200"
            @click="viewPlans"
          >Compare all plans</button>
          <button
            type="button"
            class="text-zinc-500 hover:text-zinc-300"
            @click="billing.dismissUpgradePrompt()"
          >Maybe later</button>
        </div>
      </div>
    </div>
  </Teleport>
</template>
