<script setup lang="ts">
import { Inbox, Trash2 } from "lucide-vue-next";
import { base64ToUtf8, isPrintableUtf8 } from "@/lib/utils";
import type { IncomingMessage } from "@/lib/api";

defineProps<{
  messages: IncomingMessage[];
}>();

defineEmits<{
  (e: "clear"): void;
}>();

function topicLabel(t: string): string {
  return t ? (isPrintableUtf8(t) ? base64ToUtf8(t) : `b64:${t}`) : "—";
}

function payloadLabel(p: string): string {
  return isPrintableUtf8(p) ? base64ToUtf8(p) : `(${atob(p).length} bytes binary)`;
}

function shortIp(addr: string): string {
  if (addr.length <= 28) return addr;
  return `${addr.slice(0, 12)}…${addr.slice(-10)}`;
}
</script>

<template>
  <div class="rounded-lg border border-border bg-card">
    <header class="flex items-center justify-between border-b border-border px-4 py-2">
      <div class="flex items-center gap-2">
        <Inbox class="h-4 w-4 text-muted-foreground" />
        <h3 class="text-sm font-medium">Inbox</h3>
        <span class="text-xs text-muted-foreground">
          {{ messages.length }} message{{ messages.length === 1 ? "" : "s" }}
        </span>
      </div>
      <button
        v-if="messages.length"
        class="rounded p-1 text-muted-foreground hover:bg-secondary hover:text-foreground"
        title="Clear inbox"
        @click="$emit('clear')"
      >
        <Trash2 class="h-4 w-4" />
      </button>
    </header>
    <div class="max-h-[55vh] divide-y divide-border overflow-y-auto">
      <p v-if="!messages.length" class="px-4 py-6 text-center text-sm text-muted-foreground">
        No messages yet.
      </p>
      <article v-for="m in messages" :key="m.id" class="px-4 py-3 hover:bg-muted/30">
        <div class="flex items-baseline justify-between gap-3">
          <div class="text-xs text-muted-foreground">
            from
            <span class="font-mono">{{ shortIp(m.srcIp) }}</span>
            <span class="mx-1">·</span>
            topic <span class="font-mono">{{ topicLabel(m.topic) }}</span>
          </div>
          <code class="text-[10px] text-muted-foreground">{{ m.id }}</code>
        </div>
        <div class="mt-1 whitespace-pre-wrap break-all font-mono text-sm">
          {{ payloadLabel(m.payload) }}
        </div>
      </article>
    </div>
  </div>
</template>
