<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { api } from '../lib/api'
import { displayInitialFrom } from '../lib/display'
import { editorPath, loginPath } from '../lib/paths'
import { toApiUrl } from '../lib/runtime'
import { useToast } from '../composables/useToast'

const router = useRouter()
const toast = useToast()
const notifications = ref([])
const isLoading = ref(false)
const unreadOnly = ref(false)
const isMarkingAllRead = ref(false)

const unreadCount = computed(() => notifications.value.filter((item) => !item.isRead).length)

function avatarUrlOf(notification) {
  return notification.actorAvatarSrc ? toApiUrl(notification.actorAvatarSrc) : ''
}

function avatarFallbackOf(notification) {
  return displayInitialFrom(notification.actorName, notification.actorAccountName, '?')
}

function formatDate(ts) {
  return new Date(Number(ts || 0)).toLocaleString('ko-KR', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

function notificationTitle(notification) {
  return notification.notificationType === 'comment_reply' ? '내 댓글에 답글이 달렸어요.' : '내 티어표에 새 댓글이 달렸어요.'
}

function emitUnreadCount(unread) {
  if (typeof window === 'undefined') return
  window.dispatchEvent(new CustomEvent('tier-maker:comment-inbox-updated', { detail: { unreadCount: unread } }))
}

async function loadInbox() {
  isLoading.value = true
  try {
    const data = await api.listCommentInbox({ unreadOnly: unreadOnly.value })
    notifications.value = Array.isArray(data.notifications) ? data.notifications : []
    emitUnreadCount(unreadCount.value)
  } catch (error) {
    toast.error('댓글 알림을 불러오지 못했어요.')
  } finally {
    isLoading.value = false
  }
}

async function markOneAsRead(notificationId) {
  const target = notifications.value.find((item) => item.id === notificationId)
  if (!target || target.isRead) return
  target.isRead = true
  emitUnreadCount(unreadCount.value)
  try {
    await api.markCommentInboxRead({ notificationIds: [notificationId] })
  } catch (error) {
    target.isRead = false
    emitUnreadCount(unreadCount.value)
  }
}

async function markAllAsRead() {
  if (!unreadCount.value) return
  isMarkingAllRead.value = true
  const original = notifications.value.map((item) => ({ ...item }))
  notifications.value = notifications.value.map((item) => ({ ...item, isRead: true }))
  emitUnreadCount(0)
  try {
    await api.markCommentInboxRead({ all: true })
    if (unreadOnly.value) {
      notifications.value = []
    }
  } catch (error) {
    notifications.value = original
    emitUnreadCount(unreadCount.value)
    toast.error('읽음 처리를 완료하지 못했어요.')
  } finally {
    isMarkingAllRead.value = false
  }
}

async function openNotification(notification) {
  await markOneAsRead(notification.id)
  router.push({
    path: editorPath(notification.topicSlug || notification.topicId, notification.tierListId),
    query: { commentId: notification.commentId },
  })
}

onMounted(async () => {
  try {
    await api.me()
  } catch (error) {
    toast.error('로그인이 필요해요.')
    router.push(loginPath('/comments'))
    return
  }
  loadInbox()
})

watch(unreadOnly, loadInbox)
</script>

<template>
  <section class="pageWrap">
    <section class="pageHead">
      <div class="pageHead__main">
        <div class="pageHead__eyebrow">Inbox</div>
        <h1 class="pageHead__title">댓글 관리</h1>
        <p class="pageHead__desc">내 티어표에 달린 댓글과, 내 댓글에 달린 답글을 한곳에서 확인하고 바로 이동할 수 있어요.</p>
      </div>
    </section>

    <section class="commentInboxToolbar">
      <label class="commentInboxToolbar__toggle">
        <input v-model="unreadOnly" type="checkbox" />
        <span>안 읽은 댓글만 보기</span>
      </label>
      <button class="btn btn--ghost btn--small" type="button" :disabled="!unreadCount || isMarkingAllRead" @click="markAllAsRead">
        모두 읽음 처리
      </button>
    </section>

    <section class="commentInboxPanel">
      <div v-if="isLoading" class="commentInboxEmpty">댓글 알림을 불러오는 중이에요.</div>
      <div v-else-if="notifications.length === 0" class="commentInboxEmpty">
        {{ unreadOnly ? '안 읽은 댓글 알림이 없어요.' : '아직 도착한 댓글 알림이 없어요.' }}
      </div>

      <div v-else class="commentInboxList">
        <article
          v-for="notification in notifications"
          :key="notification.id"
          class="commentInboxCard"
          :class="{ 'commentInboxCard--unread': !notification.isRead }"
        >
          <button class="commentInboxCard__body" type="button" @click="openNotification(notification)">
            <div class="commentInboxCard__main">
              <div class="commentInboxCard__titleRow">
                <div class="commentInboxCard__title">{{ notificationTitle(notification) }}</div>
                <span v-if="!notification.isRead" class="commentInboxCard__dot" aria-label="안 읽음"></span>
              </div>
              <div class="commentInboxCard__meta">
                <img
                  v-if="avatarUrlOf(notification)"
                  class="commentInboxCard__avatar"
                  :src="avatarUrlOf(notification)"
                  :alt="notification.actorName || '작성자'"
                  draggable="false"
                />
                <div v-else class="commentInboxCard__avatar commentInboxCard__avatar--fallback">{{ avatarFallbackOf(notification) }}</div>
                <span class="commentInboxCard__actor">{{ notification.actorName }}</span>
                <span class="commentInboxCard__separator">·</span>
                <span class="commentInboxCard__date">{{ formatDate(notification.createdAt) }}</span>
              </div>
              <div class="commentInboxCard__target">
                {{ notification.tierListTitle || '제목 없는 티어표' }}
                <span class="commentInboxCard__targetMeta">/ {{ notification.topicName || notification.topicSlug || notification.topicId }}</span>
              </div>
              <div class="commentInboxCard__content">{{ notification.commentContent }}</div>
            </div>
          </button>
        </article>
      </div>
    </section>
  </section>
</template>

<style scoped>
.commentInboxToolbar {
  margin-bottom: 18px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
}

.commentInboxToolbar__toggle {
  display: inline-flex;
  align-items: center;
  gap: 10px;
  color: var(--theme-text-muted);
  font-size: 14px;
  font-weight: 700;
}

.commentInboxPanel {
  border-radius: 28px;
  border: 1px solid var(--theme-card-border);
  background: var(--theme-card-bg);
  box-shadow: inset 0 1px 0 var(--theme-card-shadow);
  padding: 24px;
}

.commentInboxEmpty {
  color: var(--theme-text-muted);
}

.commentInboxList {
  display: grid;
  gap: 14px;
}

.commentInboxCard {
  border-radius: 22px;
  border: 1px solid var(--theme-card-border);
  background: var(--theme-surface);
  overflow: hidden;
}

.commentInboxCard--unread {
  border-color: color-mix(in srgb, var(--theme-accent) 48%, var(--theme-card-border));
}

.commentInboxCard__body {
  width: 100%;
  padding: 18px;
  border: 0;
  background: transparent;
  color: inherit;
  text-align: left;
  cursor: pointer;
}

.commentInboxCard__titleRow {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.commentInboxCard__title {
  font-size: 18px;
  font-weight: 900;
}

.commentInboxCard__dot {
  width: 10px;
  height: 10px;
  border-radius: 999px;
  background: #ff4d67;
  flex: 0 0 auto;
}

.commentInboxCard__meta {
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--theme-text-muted);
  font-size: 13px;
}

.commentInboxCard__avatar {
  width: 24px;
  height: 24px;
  border-radius: 999px;
  object-fit: cover;
  border: 1px solid var(--theme-avatar-border);
  background: var(--theme-border);
  flex: 0 0 auto;
}

.commentInboxCard__avatar--fallback {
  display: grid;
  place-items: center;
  font-size: 11px;
  font-weight: 900;
}

.commentInboxCard__target {
  margin-top: 12px;
  font-size: 15px;
  font-weight: 800;
}

.commentInboxCard__targetMeta {
  color: var(--theme-text-faint);
  font-weight: 700;
}

.commentInboxCard__content {
  margin-top: 10px;
  color: var(--theme-text-muted);
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  word-break: break-word;
  white-space: pre-wrap;
}

@media (max-width: 860px) {
  .commentInboxToolbar {
    flex-direction: column;
    align-items: stretch;
  }

  .commentInboxPanel {
    padding: 20px;
  }
}
</style>
