<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 tierListThumbnailUrl(notification) {
  return notification.tierListThumbnailSrc ? toApiUrl(notification.tierListThumbnailSrc) : ''
}

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 notificationLead(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="toggleSwitch commentInboxToolbar__toggle">
        <input v-model="unreadOnly" type="checkbox" />
        <span class="toggleSwitch__label">안 읽은 댓글만 보기</span>
        <span class="toggleSwitch__track"><span class="toggleSwitch__thumb"></span></span>
      </label>
      <button class="btn btn--save commentInboxToolbar__action" 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__thumbWrap">
              <img
                v-if="tierListThumbnailUrl(notification)"
                class="commentInboxCard__thumb"
                :src="tierListThumbnailUrl(notification)"
                :alt="notification.tierListTitle || '티어표 썸네일'"
                draggable="false"
              />
              <div v-else class="commentInboxCard__thumbFallback">티어표</div>
            </div>
            <div class="commentInboxCard__main">
              <div class="commentInboxCard__titleRow">
                <div>
                  <div class="commentInboxCard__title">{{ notificationTitle(notification) }}</div>
                  <div class="commentInboxCard__lead">{{ notificationLead(notification) }}</div>
                </div>
                <div class="commentInboxCard__status">
                  <span v-if="!notification.isRead" class="commentInboxCard__dot" aria-label="안 읽음"></span>
                  <span class="commentInboxCard__badge">{{ notification.notificationType === 'comment_reply' ? '답글' : '댓글' }}</span>
                </div>
              </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__thread">
                <div v-if="notification.parentCommentContent" class="commentInboxCard__threadBlock">
                  <div class="commentInboxCard__threadLabel">원래 댓글</div>
                  <div class="commentInboxCard__threadText">{{ notification.parentCommentContent }}</div>
                </div>
                <div class="commentInboxCard__threadBlock commentInboxCard__threadBlock--accent">
                  <div class="commentInboxCard__threadLabel">{{ notification.notificationType === 'comment_reply' ? '새 답글' : '새 댓글' }}</div>
                  <div class="commentInboxCard__threadText">{{ notification.commentContent }}</div>
                </div>
              </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 {
  min-width: 220px;
}

.commentInboxToolbar__action {
  min-width: 148px;
}

.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;
  background: linear-gradient(180deg, color-mix(in srgb, var(--theme-surface) 92%, var(--theme-surface-soft)) 0%, var(--theme-surface) 100%);
  overflow: hidden;
  box-shadow:
    inset 0 1px 0 color-mix(in srgb, white 5%, transparent),
    0 14px 28px rgba(0, 0, 0, 0.06);
}

.commentInboxCard--unread {
  box-shadow:
    inset 0 0 0 1px color-mix(in srgb, var(--theme-accent) 38%, transparent),
    0 14px 28px rgba(0, 0, 0, 0.08);
}

.commentInboxCard__body {
  width: 100%;
  padding: 18px;
  border: 0;
  background: transparent;
  color: inherit;
  text-align: left;
  cursor: pointer;
  display: grid;
  grid-template-columns: 140px minmax(0, 1fr);
  gap: 18px;
  align-items: start;
}

.commentInboxCard__thumbWrap {
  width: 100%;
  aspect-ratio: 16 / 9;
  align-self: start;
  flex: 0 0 auto;
  border-radius: 18px;
  overflow: hidden;
  background: var(--theme-thumb-fallback-bg);
  box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--theme-card-border) 26%, transparent);
}

.commentInboxCard__thumb,
.commentInboxCard__thumbFallback {
  width: 100%;
  height: 100%;
}

.commentInboxCard__thumb {
  object-fit: cover;
  display: block;
}

.commentInboxCard__thumbFallback {
  display: grid;
  place-items: center;
  color: var(--theme-text-faint);
  font-size: 13px;
  font-weight: 800;
}

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

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

.commentInboxCard__lead {
  margin-top: 6px;
  color: var(--theme-text-muted);
  font-size: 13px;
}

.commentInboxCard__status {
  display: inline-flex;
  align-items: center;
  gap: 10px;
}

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

.commentInboxCard__badge {
  display: inline-flex;
  align-items: center;
  min-height: 28px;
  padding: 0 12px;
  border-radius: 999px;
  background: color-mix(in srgb, var(--theme-accent) 18%, var(--theme-surface-soft));
  color: var(--theme-text);
  font-size: 12px;
  font-weight: 800;
}

.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;
}

.commentInboxCard__thread {
  margin-top: 14px;
  display: grid;
  gap: 10px;
}

.commentInboxCard__threadBlock {
  padding: 14px 15px;
  border-radius: 18px;
  background: color-mix(in srgb, var(--theme-surface) 88%, var(--theme-surface-soft));
  box-shadow:
    inset 0 0 0 1px color-mix(in srgb, var(--theme-card-border) 20%, transparent),
    0 8px 18px rgba(0, 0, 0, 0.04);
}

.commentInboxCard__threadBlock--accent {
  background: color-mix(in srgb, var(--theme-accent) 10%, var(--theme-surface));
  box-shadow:
    inset 0 0 0 1px color-mix(in srgb, var(--theme-accent) 24%, transparent),
    0 10px 20px rgba(59, 130, 246, 0.08);
}

.commentInboxCard__threadLabel {
  font-size: 11px;
  font-weight: 900;
  letter-spacing: 0.14em;
  text-transform: uppercase;
  color: var(--theme-text-faint);
}

.commentInboxCard__threadText {
  margin-top: 8px;
  color: var(--theme-text);
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}

.btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  min-height: 44px;
  padding: 12px 18px;
  border-radius: 14px;
  border: 1px solid var(--theme-border);
  background: var(--theme-surface-soft);
  color: var(--theme-text);
  cursor: pointer;
  font-size: 15px;
  font-weight: 700;
  transition: background 160ms ease;
}

.btn:hover {
  background: var(--theme-surface-soft-3);
}

.btn:disabled {
  opacity: 0.58;
  cursor: default;
}

.btn--save {
  min-width: 112px;
  font-weight: 900;
  background: rgba(96, 165, 250, 0.22);
  border-color: rgba(96, 165, 250, 0.36);
}

.btn--save:hover {
  background: rgba(96, 165, 250, 0.3);
}

.toggleSwitch {
  display: inline-flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 10px 12px;
  border-radius: 14px;
  border: 1px solid var(--theme-border);
  background: var(--theme-pill-bg);
  cursor: pointer;
  user-select: none;
}

.toggleSwitch input {
  position: absolute;
  opacity: 0;
  pointer-events: none;
}

.toggleSwitch__track {
  position: relative;
  width: 42px;
  height: 24px;
  border-radius: 999px;
  background: var(--theme-surface-soft-3);
  border: 1px solid var(--theme-border-strong);
  transition: background 160ms ease, border-color 160ms ease;
  flex: 0 0 auto;
}

.toggleSwitch__thumb {
  position: absolute;
  top: 50%;
  left: 3px;
  width: 16px;
  height: 16px;
  border-radius: 999px;
  background: rgba(255, 255, 255, 0.92);
  transform: translateY(-50%);
  transition: transform 180ms ease;
}

:root[data-theme='light'] .toggleSwitch__thumb {
  background: rgba(15, 23, 42, 0.82);
}

.toggleSwitch__label {
  min-width: 0;
  color: var(--theme-text-muted);
  font-size: 14px;
  font-weight: 700;
}

.toggleSwitch input:checked ~ .toggleSwitch__track {
  background: rgba(96, 165, 250, 0.34);
  border-color: rgba(96, 165, 250, 0.46);
}

.toggleSwitch input:checked ~ .toggleSwitch__track .toggleSwitch__thumb {
  transform: translate(18px, -50%);
}

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

  .commentInboxPanel {
    padding: 20px;
  }

  .commentInboxCard__body {
    grid-template-columns: 1fr;
  }
}
</style>
