<template>
    <div 
      v-if="visible" 
      class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center z-[100]"
      @click.self="cancel" 
      @keydown.esc="cancel"
      tabindex="0" 
      ref="overlay"
    >
      <div class="bg-white dark:bg-gray-800 p-8 rounded-lg shadow-xl text-center">
        <h3 class="text-2xl font-semibold text-gray-800 dark:text-gray-100 mb-4">
          Press a Key
        </h3>
        <p class="text-gray-600 dark:text-gray-300 mb-6">
          Waiting for a single key press to assign as the hotkey.
          <br>
          (Esc to cancel)
        </p>
        <div class="animate-pulse text-blue-500 dark:text-blue-400 text-xl">
          Listening...
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, watch, nextTick, onUnmounted } from 'vue';
  
  const props = defineProps({
    visible: Boolean,
  });
  const emit = defineEmits(['captured', 'cancel']);
  
  const overlay = ref(null);
  
  const handleKeyPress = (event) => {
    if (!props.visible) return;
  
    event.preventDefault();
    event.stopPropagation(); // Prevent further propagation if overlay is active
  
    let key = event.key;
    if (event.code === 'Space') {
        key = ' '; 
    } else if (key.length > 1 && key !== ' ') { // Ignore modifiers, Enter, Tab etc.
        if (key === 'Escape') { // Handle Escape specifically for cancellation
            cancel();
        }
        return; 
    }
    key = key.toLowerCase();
    emit('captured', key);
  };
  
  const cancel = () => {
    emit('cancel');
  };
  
  watch(() => props.visible, async (newValue) => {
    if (newValue) {
      await nextTick(); // Ensure overlay is in DOM
      overlay.value?.focus(); // Focus the overlay to capture keydown events directly
      document.addEventListener('keydown', handleKeyPress, { capture: true }); // Use capture phase
    } else {
      document.removeEventListener('keydown', handleKeyPress, { capture: true });
    }
  });
  
  onUnmounted(() => {
    document.removeEventListener('keydown', handleKeyPress, { capture: true });
  });
  </script>
  
  <style scoped>
  /* Ensure overlay is above other modals if any (PlayerForm uses z-50) */
  .z-\[100\] { 
    z-index: 100;
  }
  </style>