<template>
    <div 
      v-if="visible" 
      class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center z-[100]"
      @click.self="handleCancel" 
      @keydown.esc="handleCancel"
      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">
          Send MQTT Signal
        </h3>
        <p class="text-gray-600 dark:text-gray-300 mb-6">
          Send a single character message to the MQTT topic '{{ MqttService.MQTT_TOPIC_GAME }}'.
          <br>
          (Press Esc on keyboard or click backdrop to cancel)
        </p>
        <div class="animate-pulse text-purple-500 dark:text-purple-400 text-xl">
          Listening for MQTT...
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, watch, nextTick, onUnmounted } from 'vue';
  import { MqttService } from '../services/MqttService'; // To display topic name
  
  const props = defineProps({
    visible: Boolean,
  });
  const emit = defineEmits(['cancel']); // Only emits 'cancel', 'captured' will be handled by parent via service
  
  const overlay = ref(null);
  
  // No direct key press handling here for MQTT capture, parent will manage via MqttService
  const handleCancel = () => {
    emit('cancel');
  };
  
  watch(() => props.visible, async (newValue) => {
    if (newValue) {
      await nextTick();
      overlay.value?.focus(); // Focus for Esc key to cancel
       // Add specific keyboard listener just for Esc on this overlay
      document.addEventListener('keydown', escKeyHandler);
    } else {
      document.removeEventListener('keydown', escKeyHandler);
    }
  });
  
  // Specific Esc handler for this overlay
  const escKeyHandler = (event) => {
      if (props.visible && event.key === 'Escape') {
          event.preventDefault();
          event.stopPropagation();
          handleCancel();
      }
  };
  
  onUnmounted(() => {
    document.removeEventListener('keydown', escKeyHandler);
  });
  </script>