<script setup lang="ts">
import { computed, watch, ref } from 'vue'
import { useFocusTrap } from '../utils/focusTrap'

interface Props {
  show: boolean
  idleSeconds: number
}

const props = defineProps<Props>()

const emit = defineEmits<{
  continueKeep: []
  continueSubtract: []
  stopTimer: []
}>()

const { activate, deactivate } = useFocusTrap()
const dialogRef = ref<HTMLElement | null>(null)

const idleFormatted = computed(() => {
  const mins = Math.floor(props.idleSeconds / 60)
  const secs = props.idleSeconds % 60
  if (mins > 0) {
    return `${mins}m ${secs}s`
  }
  return `${secs}s`
})

watch(() => props.show, (val) => {
  if (val) {
    setTimeout(() => {
      if (dialogRef.value) activate(dialogRef.value, { onDeactivate: () => emit('stopTimer') })
    }, 50)
  } else {
    deactivate()
  }
})
</script>

<template>
  <Transition name="modal">
  <div
    v-if="show"
    class="fixed inset-0 bg-black/70 backdrop-blur-[4px] flex items-center justify-center p-4 z-50"
  >
    <div ref="dialogRef" role="alertdialog" aria-modal="true" aria-labelledby="idle-title" aria-describedby="idle-desc" class="bg-bg-surface border border-border-subtle rounded-lg shadow-[0_1px_3px_rgba(0,0,0,0.3)] w-full max-w-sm p-6">
      <h2 id="idle-title" class="text-[1.125rem] font-semibold font-[family-name:var(--font-heading)] text-text-primary mb-2">You've been idle</h2>
      <p id="idle-desc" class="text-[0.75rem] text-text-secondary mb-6">
        No keyboard or mouse input detected for <span class="font-mono font-medium text-text-primary">{{ idleFormatted }}</span>.
      </p>
      <div class="flex flex-col gap-2.5">
        <button
          @click="emit('continueKeep')"
          class="w-full px-4 py-2.5 bg-accent text-bg-base text-[0.8125rem] font-medium rounded-lg hover:bg-accent-hover transition-colors duration-150"
        >
          Continue (keep time)
        </button>
        <button
          @click="emit('continueSubtract')"
          class="w-full px-4 py-2.5 border border-border-subtle text-text-primary text-[0.8125rem] rounded-lg hover:bg-bg-elevated transition-colors duration-150"
        >
          Continue (subtract {{ idleFormatted }})
        </button>
        <button
          @click="emit('stopTimer')"
          class="w-full px-4 py-2.5 border border-status-error text-status-error-text text-[0.8125rem] font-medium rounded-lg hover:bg-status-error/10 transition-colors duration-150"
        >
          Stop &amp; Save
        </button>
      </div>
    </div>
  </div>
  </Transition>
</template>
