<template>
  <section>
    <div class="flex items-center justify-between mb-3">
      <h2 class="text-sm font-bold text-gray-500 uppercase tracking-wider">
        Meine iOS-Geräte
      </h2>
    </div>

    <div v-if="loading && devices.length === 0" class="py-12 text-center text-gray-500">
      <UIcon name="i-heroicons-arrow-path" class="w-8 h-8 animate-spin mx-auto mb-3 text-[var(--rebreak-primary)]" />
      <p class="font-semibold">Lade iOS-Geräte…</p>
    </div>

    <div v-else-if="devices.length === 0 && !hasUnknownUsbDevice" class="py-10 text-center rounded-2xl bg-white ring-1 ring-gray-100">
      <p class="text-sm text-gray-500">
        {{ hasRefreshed ? 'Keine iOS-Geräte registriert.' : 'Noch keine iOS-Geräte geladen.' }}
      </p>
      <p v-if="hasRefreshed" class="text-xs text-gray-400 mt-2">
        Installiere die ReBreak-App, melde dich an und registriere das Gerät.
      </p>
    </div>

    <div v-else class="space-y-3">
      <UnknownIosDeviceCard
        v-if="hasUnknownUsbDevice && iphone"
        :iphone="iphone"
      />

      <IosDeviceCard
        v-for="device in devices"
        :key="device.deviceId"
        :device="device"
        :iphone="iphone"
        :is-connected="device.deviceId === connectedDeviceId"
        :is-searching="device.deviceId === searchingForDeviceId"
        :in-grace-period="inGracePeriod"
        @sync="emit('sync', $event)"
        @open="emit('open', $event)"
        @remove="emit('remove', $event)"
        @connect="emit('connect', $event)"
      />
    </div>
  </section>
</template>

<script setup lang="ts">
import { computed } from "vue";
import type { ComputedDevice } from "~/composables/useDeviceStatus";
import type { IphoneDeviceState } from "~/composables/useTauri";

const props = defineProps<{
  devices: ComputedDevice[];
  iphone: IphoneDeviceState | null;
  loading: boolean;
  hasRefreshed: boolean;
  inGracePeriod?: boolean;
  searchingForDeviceId?: string | null;
}>();

const emit = defineEmits<{
  (e: "sync", device: ComputedDevice): void;
  (e: "open", device: ComputedDevice): void;
  (e: "remove", device: ComputedDevice): void;
  (e: "connect", device: ComputedDevice): void;
}>();

function matchesIphone(device: ComputedDevice, iphone: IphoneDeviceState): boolean {
  if (device.mdmId && device.mdmId === iphone.udid) return true;
  const modelMatch = (device.model ?? "").toLowerCase() === iphone.productType.toLowerCase();
  const nameMatch = (device.name ?? "").toLowerCase() === iphone.name.toLowerCase();
  return modelMatch || nameMatch;
}

const connectedDeviceId = computed(() => {
  if (!props.iphone) return null;
  return props.devices.find((d) => matchesIphone(d, props.iphone!))?.deviceId ?? null;
});

const hasUnknownUsbDevice = computed(() => {
  return !!props.iphone && !connectedDeviceId.value;
});
</script>
