<script setup lang="ts">
// Collaborator invite acceptance — Tier 2 Block C.
//
// Flow:
//   1. Preview the invite (unauthed) so we can show the event name + role.
//   2. If the visitor isn't signed in, redirect them to signup (preserving
//      the invite path as redirect). The signup must use the invited email.
//   3. After signup/login the user lands back here; POST /invites/{token}/accept
//      and on success bounce them to /dashboard/events/{event_id}.

interface InviteSummary {
  event_id: string
  event_name: string
  role: 'owner' | 'editor' | 'viewer'
  email: string
  expires_at: string
}

const route = useRoute()
const auth = useAuth()
const token = route.params.token as string

const loading = ref(true)
const summary = ref<InviteSummary | null>(null)
const loadError = ref<string | null>(null)

const accepting = ref(false)
const acceptError = ref<string | null>(null)

onMounted(async () => {
  try {
    summary.value = await useApi<InviteSummary>(`/invites/${token}`)
  } catch (e: any) {
    loadError.value = useErrMessage(e, 'Invitation is invalid or expired.')
  } finally {
    loading.value = false
  }
})

const signedIn = computed(() => !!auth.user.value)
const emailMatches = computed(() => {
  if (!summary.value || !auth.user.value) return false
  return auth.user.value.email.trim().toLowerCase() === summary.value.email.trim().toLowerCase()
})

function goToSignup() {
  // Pre-fill the email so the visitor isn't tempted to register a different
  // one. The accept handler refuses to consume the invite if emails differ.
  if (!summary.value) return
  const target = `/signup?email=${encodeURIComponent(summary.value.email)}&redirect=${encodeURIComponent(route.fullPath)}`
  navigateTo(target)
}

function goToLogin() {
  if (!summary.value) return
  const target = `/login?email=${encodeURIComponent(summary.value.email)}&redirect=${encodeURIComponent(route.fullPath)}`
  navigateTo(target)
}

async function accept() {
  if (!summary.value) return
  accepting.value = true
  acceptError.value = null
  try {
    const res = await useApi<{ event_id: string }>(`/invites/${token}/accept`, { method: 'POST' })
    navigateTo(`/dashboard/events/${res.event_id}`)
  } catch (e: any) {
    acceptError.value = useErrMessage(e, 'Could not accept invitation')
  } finally {
    accepting.value = false
  }
}

function fmtDate(iso?: string) {
  if (!iso) return ''
  try { return new Date(iso).toLocaleString() } catch { return iso }
}
</script>

<template>
  <section class="mx-auto max-w-xl py-10">
    <div v-if="loading" class="text-sm text-zinc-500">Looking up your invitation…</div>

    <div v-else-if="loadError" class="card border-red-900/60 bg-red-950/30">
      <h1 class="mb-2 text-xl font-semibold text-red-200">Invitation unavailable</h1>
      <p class="text-sm text-red-300">{{ loadError }}</p>
      <p class="mt-4 text-xs text-zinc-500">
        Ask the person who sent the invitation to resend it from the event's Team tab.
      </p>
    </div>

    <div v-else-if="summary" class="card border-brand-900/60 bg-brand-950/20">
      <p class="text-xs uppercase tracking-widest text-brand-500">Team invitation</p>
      <h1 class="mb-1 text-2xl font-semibold">{{ summary.event_name }}</h1>
      <p class="mb-5 text-sm text-zinc-400">
        You've been invited as
        <strong class="capitalize text-brand-300">{{ summary.role }}</strong>.
      </p>

      <div v-if="!signedIn" class="space-y-3">
        <p class="text-sm">
          Sign in or create a GuestGuard account for
          <strong class="text-zinc-100">{{ summary.email }}</strong>
          to accept.
        </p>
        <div class="flex gap-2">
          <button class="btn-primary flex-1" @click="goToSignup">Create account</button>
          <button class="btn-ghost flex-1" @click="goToLogin">Sign in</button>
        </div>
      </div>

      <div v-else-if="!emailMatches" class="rounded-md border border-amber-900/60 bg-amber-950/20 p-3 text-sm">
        <p class="text-amber-200">
          You're signed in as <strong>{{ auth.user.value?.email }}</strong>,
          but this invitation was sent to
          <strong>{{ summary.email }}</strong>.
        </p>
        <p class="mt-2 text-xs text-amber-300/80">
          Sign out and sign back in with the right account to accept.
        </p>
      </div>

      <div v-else class="space-y-3">
        <p class="text-sm">Ready to join? Accept the invitation below.</p>
        <button class="btn-primary w-full" :disabled="accepting" @click="accept">
          {{ accepting ? 'Accepting…' : `Accept and open event` }}
        </button>
        <p v-if="acceptError" class="text-sm text-red-400">{{ acceptError }}</p>
      </div>

      <p class="mt-5 border-t border-zinc-800 pt-4 text-xs text-zinc-500">
        Expires {{ fmtDate(summary.expires_at) }}.
      </p>
    </div>
  </section>
</template>
