<template>
  <div class="floating-alarm-stack">
    <FloatingAlarmCard
      v-for="(a, idx) in visible"
      :key="`${a.carId}-${a.timestamp}`"
      :alarm="a"
      :initial-offset="{ right: 24, bottom: 24 + idx * 132 }"
      @close="onClose(a)"
      @ack="onAck(a)"
      @snooze="onSnooze(a)"
      @locate="onLocate"
    />
    <div v-if="snoozed.length" class="snooze-tray" @click="restoreSnoozed">
      <el-badge :value="snoozed.length" type="warning">
        <el-button size="small" circle>≡</el-button>
      </el-badge>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import FloatingAlarmCard from './FloatingAlarmCard.vue'
import type { AlarmEvent } from '@/composables/useMapEditStream'

const props = defineProps<{ alarms: AlarmEvent[] }>()
const emit = defineEmits<{
  (e: 'locate', a: AlarmEvent): void
  (e: 'ack', a: AlarmEvent): void
}>()

const dismissed = ref<Set<string>>(new Set())
const snoozedIds = ref<Set<string>>(new Set())

function keyOf(a: AlarmEvent) { return `${a.carId}` }

const visible = computed(() =>
  props.alarms
    .filter((a) => a.action !== 'clear')
    .filter((a) => !dismissed.value.has(keyOf(a)))
    .filter((a) => !snoozedIds.value.has(keyOf(a)))
)

const snoozed = computed(() => props.alarms.filter((a) => snoozedIds.value.has(keyOf(a))))

function onClose(a: AlarmEvent) {
  dismissed.value = new Set([...dismissed.value, keyOf(a)])
}
function onAck(a: AlarmEvent) {
  dismissed.value = new Set([...dismissed.value, keyOf(a)])
  emit('ack', a)
}
function onSnooze(a: AlarmEvent) {
  snoozedIds.value = new Set([...snoozedIds.value, keyOf(a)])
}
function onLocate(a: AlarmEvent) {
  emit('locate', a)
}
function restoreSnoozed() {
  snoozedIds.value = new Set()
}
</script>

<style scoped>
.floating-alarm-stack {
  position: absolute;
  inset: 0;
  pointer-events: none;
}
.floating-alarm-stack > * {
  pointer-events: auto;
}
.snooze-tray {
  position: absolute;
  right: 24px;
  top: 24px;
}
</style>
