<script setup lang="ts">
// Account page — owns the data-export + account-deletion controls that
// used to sit on the billing tab. Privacy concerns ≠ billing concerns;
// hosts shouldn't have to scroll past pricing to find "delete my account".
definePageMeta({ middleware: ['auth'] })

const router = useRouter()
const auth = useAuth()
const config = useRuntimeConfig()

const exporting = ref(false)
const deleteConfirmOpen = ref(false)
const deleteConfirmation = ref('')
const deleting = ref(false)
const deleteError = ref<string | null>(null)
const toast = ref<string | null>(null)
let toastTimer: ReturnType<typeof setTimeout> | null = null

function showToast(text: string) {
  toast.value = text
  if (toastTimer) clearTimeout(toastTimer)
  toastTimer = setTimeout(() => { toast.value = null }, 5000)
}

async function exportData() {
  exporting.value = true
  try {
    const apiBase = config.public.apiBase as string
    const token = auth.liveAccessToken()
    // Plain fetch (not useApi) so the response is treated as a download.
    const res = await fetch(`${apiBase}/me/data-export`, {
      headers: token ? { Authorization: `Bearer ${token}` } : {},
      credentials: 'include',
    })
    if (!res.ok) throw new Error(`HTTP ${res.status}`)
    const blob = await res.blob()
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = 'guestguard-data-export.json'
    a.click()
    URL.revokeObjectURL(url)
    showToast('Export downloaded.')
  } catch (e: any) {
    showToast(useErrMessage(e, 'Export failed'))
  } finally {
    exporting.value = false
  }
}

async function confirmDelete() {
  deleting.value = true
  deleteError.value = null
  try {
    await useApi('/me', { method: 'DELETE' })
    // Soft-delete revoked our refresh token; clear local session and
    // bounce to the marketing landing.
    auth.clearSession()
    await router.push('/')
  } catch (e: any) {
    deleteError.value = useErrMessage(e, 'Could not delete account')
  } finally {
    deleting.value = false
  }
}
</script>

<template>
  <section class="space-y-6">
    <div>
      <NuxtLink to="/dashboard" class="mb-2 inline-block text-sm text-zinc-400 hover:text-zinc-200">
        ← Back to events
      </NuxtLink>
      <h1 class="text-2xl font-semibold">Account</h1>
      <p class="mt-1 text-sm text-zinc-400">
        Manage your profile and personal data.
      </p>
    </div>

    <ClientOnly>
      <!-- Profile summary -->
      <div class="card">
        <h2 class="mb-3 text-lg font-semibold">Profile</h2>
        <dl class="grid grid-cols-1 gap-3 text-sm sm:grid-cols-2">
          <div>
            <dt class="text-xs uppercase tracking-wider text-zinc-500">Name</dt>
            <dd class="mt-1 text-zinc-100">{{ auth.user.value?.name || '—' }}</dd>
          </div>
          <div>
            <dt class="text-xs uppercase tracking-wider text-zinc-500">Email</dt>
            <dd class="mt-1 break-all text-zinc-100">{{ auth.user.value?.email || '—' }}</dd>
          </div>
        </dl>
      </div>

      <!-- Your data -->
      <div class="card">
        <h2 class="mb-1 text-lg font-semibold">Your data</h2>
        <p class="mb-4 text-xs text-zinc-500">
          Export a copy of everything we hold about you, or delete your account.
        </p>
        <div class="space-y-3">
          <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="exporting"
            @click="exportData"
          >
            <span>
              <span class="block text-sm font-medium text-zinc-100">Export my data</span>
              <span class="block text-xs text-zinc-500">
                Download a JSON file with your events, guests, RSVPs, and account info.
              </span>
            </span>
            <span class="text-xs text-zinc-400">{{ exporting ? '…' : '↓' }}</span>
          </button>

          <button
            type="button"
            class="flex w-full items-center justify-between rounded-md border border-red-800/40 bg-red-950/10 px-3 py-3 text-left transition hover:border-red-700 hover:bg-red-950/20"
            @click="deleteConfirmOpen = true"
          >
            <span>
              <span class="block text-sm font-medium text-red-300">Delete my account</span>
              <span class="block text-xs text-red-400/70">
                Soft-deleted immediately, permanently erased after 30 days. You'll be signed out everywhere.
              </span>
            </span>
            <span class="text-xs text-red-400">→</span>
          </button>
        </div>
      </div>

      <template #fallback>
        <div class="card text-sm text-zinc-500">Loading…</div>
      </template>
    </ClientOnly>

    <!-- Delete-account confirmation -->
    <Teleport to="body">
      <div
        v-if="deleteConfirmOpen"
        class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm"
        @click.self="deleteConfirmOpen = false"
      >
        <div
          role="alertdialog"
          aria-modal="true"
          aria-labelledby="del-acct-title"
          class="w-full max-w-md rounded-lg border border-zinc-800 bg-zinc-900 p-5 shadow-2xl"
        >
          <h3 id="del-acct-title" class="mb-1 text-base font-semibold">Delete account?</h3>
          <p class="mb-3 text-sm text-zinc-400">
            Your account will be soft-deleted now and permanently erased
            after 30 days. All your events, guests, and RSVP history go
            with it. You'll be signed out from every device.
          </p>
          <p class="mb-3 text-xs text-zinc-500">
            Type <code class="rounded bg-zinc-800 px-1 py-0.5 font-mono text-zinc-300">delete</code>
            to confirm.
          </p>
          <input
            v-model="deleteConfirmation"
            type="text"
            placeholder="delete"
            class="input mb-3 font-mono"
            autocomplete="off"
          />
          <div class="flex items-center justify-end gap-2">
            <button class="text-sm text-zinc-400 hover:text-zinc-200" :disabled="deleting" @click="deleteConfirmOpen = false">Cancel</button>
            <button
              class="rounded-md bg-red-500/90 px-3 py-1.5 text-sm font-medium text-white shadow-sm transition hover:bg-red-500 disabled:opacity-40"
              :disabled="deleting || deleteConfirmation.trim().toLowerCase() !== 'delete'"
              @click="confirmDelete"
            >
              {{ deleting ? 'Deleting…' : 'Delete forever' }}
            </button>
          </div>
          <p v-if="deleteError" class="mt-3 text-sm text-red-400">{{ deleteError }}</p>
        </div>
      </div>
    </Teleport>

    <!-- Toast -->
    <Transition
      enter-active-class="transition duration-200 ease-out"
      enter-from-class="translate-y-2 opacity-0"
      enter-to-class="translate-y-0 opacity-100"
      leave-active-class="transition duration-200 ease-in"
      leave-from-class="translate-y-0 opacity-100"
      leave-to-class="translate-y-2 opacity-0"
    >
      <button
        v-if="toast"
        type="button"
        class="fixed bottom-6 right-6 z-50 max-w-sm rounded-lg border border-brand-700/60 bg-brand-950/90 px-4 py-3 text-left text-sm text-brand-100 shadow-lg backdrop-blur"
        @click="toast = null"
      >
        <span aria-hidden="true" class="mr-2">✓</span>{{ toast }}
      </button>
    </Transition>
  </section>
</template>
