<script setup>
  import { ref, onMounted } from 'vue'
  import MQTTService from '../../services/mqtt.js'

  const emit = defineEmits(['select'])

  const mqtt = new MQTTService()

  const devices = ref([])
  const deviceSet = new Set()
  const selected = ref(null)

  function upsertDevice(device, status) {
    const existing = devices.value.find((d) => d.id === device)

    if (existing) {
      // ✅ update reactively
      existing.value = status
    } else {
      deviceSet.add(device)

      devices.value = [
        ...devices.value,
        {
          id: device,
          title: device,
          value: status,
          subtitle: 'MQTT Device',
          icon: status === 'ONLINE' ? 'pi-check-circle' : 'pi-times-circle',
        },
      ]
    }
  }
  function selectDevice(device) {
    selected.value = device.id
    emit('select', device.id)
  }

  onMounted(() => {
    mqtt.subscribe('device/+/property/status', (payload, topic) => {
      const parts = topic.split('/')
      const device = parts[1]
      upsertDevice(device, payload)
    })
  })
</script>

<template>
  <div class="layout-grid-row">
    <div
      v-for="(device, index) in devices"
      :key="device.id"
      class="layout-card device-card"
      :class="{ 'selected-device': device.id === selected }"
      @click="selectDevice(device)"
    >
      <div class="stats-header">
        <span class="stats-title">{{ device.title }}</span>
        <span class="stats-icon-box">
          <i
            :class="[
              'pi',
              device.value === 'ONLINE' ? 'pi-check-circle' : 'pi-times-circle',
              device.value === 'ONLINE' ? '' : 'text-red-500',
            ]"
          ></i>
        </span>
      </div>

      <div class="stats-content">
        <div class="stats-value">{{ device.value }}</div>
        <div class="stats-subtitle">{{ device.subtitle }}</div>
      </div>
    </div>
  </div>
</template>

<style scoped>
  .device-card {
    cursor: pointer;
    transition: all 0.2s ease;
  }

  .device-card:hover {
    transform: translateY(-2px);
  }

  /* 🔥 selected state */
  .selected-device {
    border: 2px solid var(--p-primary-color);
    box-shadow: 0 0 8px var(--p-primary-color);
  }
</style>
