<script setup lang="ts">
// Shown the first time a host signs into the dashboard after T&C
// enforcement is rolled out. Existing accounts created before this
// feature don't have terms_accepted_at set — they're re-prompted once
// here, then they're set going forward.
//
// Lives in app.vue so any authed page can be the host's first stop.

const auth = useAuth()
const accepted = ref(false)
const submitting = ref(false)
const error = ref<string | null>(null)

// Only fires when the user is signed in AND we know they haven't
// accepted. /me payload includes terms_accepted_at; if absent → prompt.
const needsAcceptance = computed(() => {
  const u = auth.user.value
  return !!u && !u.terms_accepted_at && !u.privacy_policy_accepted_at
})

async function accept() {
  if (!accepted.value) return
  submitting.value = true
  error.value = null
  try {
    await useApi('/me/accept-terms', { method: 'POST' })
    // Refresh auth state so the user object reflects the new fields.
    await auth.refresh()
  } catch (e: any) {
    error.value = useErrMessage(e, 'Could not record acceptance')
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <Teleport to="body">
    <div
      v-if="needsAcceptance"
      class="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4 backdrop-blur-sm"
    >
      <div
        role="dialog"
        aria-modal="true"
        aria-labelledby="terms-title"
        class="w-full max-w-md rounded-lg border border-zinc-800 bg-zinc-900 p-5 shadow-2xl"
      >
        <h3 id="terms-title" class="mb-1 text-base font-semibold">One quick thing</h3>
        <p class="mb-4 text-sm text-zinc-400">
          We've updated how GuestGuard handles your data. Before you carry on,
          please confirm you've read and agree to the current policies.
        </p>

        <label class="flex cursor-pointer items-start gap-2 text-sm text-zinc-200">
          <input
            v-model="accepted"
            type="checkbox"
            class="mt-0.5 h-4 w-4 cursor-pointer accent-brand-500"
          />
          <span>
            I agree to GuestGuard's
            <NuxtLink to="/terms" target="_blank" class="text-brand-400 hover:text-brand-300">Terms of Service</NuxtLink>
            and
            <NuxtLink to="/privacy" target="_blank" class="text-brand-400 hover:text-brand-300">Privacy Policy</NuxtLink>.
          </span>
        </label>

        <button
          class="btn-primary mt-4 w-full disabled:opacity-50"
          :disabled="!accepted || submitting"
          @click="accept"
        >
          {{ submitting ? 'Saving…' : 'Continue' }}
        </button>
        <p v-if="error" class="mt-3 text-sm text-red-400">{{ error }}</p>
      </div>
    </div>
  </Teleport>
</template>
