<template>
  <div v-if="showBanner" class="push-opt-in-banner" role="status" aria-live="polite">
    <template v-if="permissionState === 'default'">
      <span class="push-opt-in-text"
        >Enable notifications to stay updated on chores and rewards.</span
      >
      <button class="btn btn-primary push-opt-in-btn" @click="onEnable">Enable</button>
      <button class="push-opt-in-dismiss" @click="dismiss" aria-label="Dismiss">✕</button>
    </template>
    <template v-else-if="permissionState === 'denied'">
      <span class="push-opt-in-text"
        >Notifications are blocked. Enable them in your browser settings to receive alerts.</span
      >
      <button class="push-opt-in-dismiss" @click="dismiss" aria-label="Dismiss">✕</button>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { subscribeToPushWithResult } from '@/services/pushSubscription'

const permissionState = ref<NotificationPermission | 'unsupported'>('default')
const dismissed = ref(false)

const showBanner = ref(false)

onMounted(async () => {
  if (!('Notification' in window)) {
    return
  }
  permissionState.value = Notification.permission
  if (permissionState.value === 'granted') {
    // Already granted — ensure subscription is registered silently
    subscribeToPushWithResult()
    return
  }
  showBanner.value = true
})

async function onEnable() {
  const result = await subscribeToPushWithResult()
  if (result.ok) {
    permissionState.value = 'granted'
    showBanner.value = false
  } else {
    permissionState.value = Notification.permission as NotificationPermission
  }
}

function dismiss() {
  dismissed.value = true
  showBanner.value = false
}
</script>

<style scoped>
.push-opt-in-banner {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  background: var(--list-item-bg, #f0f4ff);
  border: 1px solid var(--btn-primary, #4a90e2);
  border-radius: 8px;
  padding: 0.6rem 1rem;
  margin: 0.5rem 0;
  font-size: 0.88rem;
  flex-wrap: wrap;
}

.push-opt-in-text {
  flex: 1;
  min-width: 0;
}

.push-opt-in-btn {
  font-size: 0.85rem;
  padding: 0.35rem 0.9rem;
  white-space: nowrap;
}

.push-opt-in-dismiss {
  background: none;
  border: none;
  cursor: pointer;
  color: var(--text-muted, #888);
  font-size: 1rem;
  padding: 0 0.25rem;
  line-height: 1;
}
</style>
