<template>
  <v-alert
    v-if="showBanner && duplicateCount > 0"
    type="warning"
    variant="tonal"
    closable
    @click:close="dismissBanner"
    class="ma-4"
  >
    <template #prepend>
      <v-icon>mdi-content-duplicate</v-icon>
    </template>
    
    <div class="d-flex align-center justify-space-between">
      <div>
        <div class="text-subtitle-1 font-weight-medium">
          {{ duplicateCount }} duplicate interest record{{ duplicateCount > 1 ? 's' : '' }} detected
        </div>
        <div class="text-body-2">
          Duplicate records can affect data integrity and reporting accuracy.
        </div>
      </div>
      
      <v-btn
        color="warning"
        variant="elevated"
        size="small"
        :to="'/dashboard/admin/duplicates'"
        prepend-icon="mdi-wrench"
      >
        Clean Up Duplicates
      </v-btn>
    </div>
  </v-alert>
</template>

<script setup>
const { isAdmin } = useAuthorization();

const showBanner = ref(true);
const duplicateCount = ref(0);
const loading = ref(false);

// Check for duplicates on mount (any authenticated user)
const checkForDuplicates = async () => {
  if (loading.value) return;
  
  try {
    loading.value = true;
    const response = await $fetch('/api/admin/duplicates/find', {
      method: 'GET',
      query: { threshold: 0.8 }
    });
    
    if (response.success && response.data?.duplicateGroups) {
      duplicateCount.value = response.data.duplicateGroups.length;
    }
  } catch (error) {
    console.error('[DuplicateNotification] Failed to check for duplicates:', error);
    // Silently fail - this is just a notification banner
  } finally {
    loading.value = false;
  }
};

// Dismiss the banner for this session
const dismissBanner = () => {
  showBanner.value = false;
  // Store dismissal in session storage
  if (process.client) {
    sessionStorage.setItem('duplicates-banner-dismissed', 'true');
  }
};

// Check if banner was already dismissed this session
onMounted(() => {
  if (process.client) {
    const dismissed = sessionStorage.getItem('duplicates-banner-dismissed');
    if (dismissed === 'true') {
      showBanner.value = false;
      return;
    }
  }
  
  // Check for duplicates for any authenticated user
  // Small delay to let other components load first
  setTimeout(checkForDuplicates, 2000);
});
</script>
