<script setup>
definePageMeta({
  layout: 'admin'
})

const { data: members } = await useFetch('/admin/api/members', {
  default: () => []
})

/**
 * 최근 접속 시각 표시 문자열을 반환한다.
 * @param {string | null} value - ISO 시각
 * @returns {string} 표시 문자열
 */
const formatLastSeen = (value) => {
  if (!value) {
    return '-'
  }

  const date = new Date(value)
  if (Number.isNaN(date.getTime())) {
    return '-'
  }

  return date.toLocaleString('ko-KR', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<template>
  <section class="admin-members min-h-screen bg-paper">
    <div class="border-b border-line bg-paper px-6 py-5">
      <p class="text-xs font-semibold uppercase text-muted">Admin</p>
      <h1 class="mt-2 text-2xl font-semibold text-ink">멤버</h1>
    </div>

    <div class="px-6 py-5">
      <div class="overflow-x-auto rounded-[10px] border border-line bg-white">
        <table class="min-w-full text-left text-sm">
          <thead class="bg-[#f7f7f5] text-xs uppercase text-muted">
            <tr>
              <th class="px-3 py-2.5">닉네임</th>
              <th class="px-3 py-2.5">이메일</th>
              <th class="px-3 py-2.5">최근 활동</th>
              <th class="px-3 py-2.5">접속 IP</th>
              <th class="px-3 py-2.5">활동 현황</th>
              <th class="px-3 py-2.5 text-right">댓글 개수</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="member in members" :key="member.id" class="border-t border-line/70">
              <td class="px-3 py-3">
                <div class="flex items-center gap-2">
                  <img
                    v-if="member.avatarUrl"
                    :src="member.avatarUrl"
                    :alt="member.username"
                    class="h-7 w-7 rounded-full object-cover"
                  >
                  <span v-else class="grid h-7 w-7 place-items-center rounded-full bg-[#efefec] text-xs font-semibold text-ink">
                    {{ (member.username || '?').slice(0, 1).toUpperCase() }}
                  </span>
                  <span>{{ member.username }}</span>
                </div>
              </td>
              <td class="px-3 py-3 text-muted">{{ member.email }}</td>
              <td class="px-3 py-3 text-muted">{{ formatLastSeen(member.lastSeenAt) }}</td>
              <td class="px-3 py-3 text-muted">{{ member.lastSeenIp || '-' }}</td>
              <td class="px-3 py-3">
                <span class="rounded-full border border-line px-2 py-0.5 text-xs">{{ member.activityStatus }}</span>
              </td>
              <td class="px-3 py-3 text-right font-semibold text-ink">{{ member.commentCount }}</td>
            </tr>
            <tr v-if="members.length === 0">
              <td colspan="6" class="px-3 py-6 text-center text-sm text-muted">등록된 회원이 없습니다.</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </section>
</template>

