<script setup>
import { onMounted, ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { boardApi } from '@/api/boardApi'
import { useAuthStore } from '@/stores/auth'
import { useDialog } from '@/composables/dialog'
import { formatRelative } from '@/utils/datetime'
import MarkdownViewer from '@/components/editor/MarkdownViewer.vue'
import MarkdownEditor from '@/components/editor/MarkdownEditor.vue'
import IconBtn from '@/components/ui/IconBtn.vue'
import { DEFAULT_BOARD } from '@/constants/boards'

const route = useRoute()
const router = useRouter()
const auth = useAuthStore()
const dialog = useDialog()

const postId = route.params.id
// 게시판(카테고리): URL 우선, 없으면 글의 category, 그래도 없으면 기본
const category = computed(() => route.params.category || post.value?.category || DEFAULT_BOARD)
const post = ref(null)
const loading = ref(false)
const error = ref(null)
const commentText = ref('')
const submitting = ref(false)

const isAdmin = computed(() => auth.user?.role === 'ADMIN')
// 비관리자에게 제한된 글 (본문/댓글 숨김)
const restricted = computed(() => post.value?.blocked && !isAdmin.value)

const canModifyPost = computed(() => {
  if (!post.value || !auth.user) return false
  return auth.user.id === post.value.authorId || isAdmin.value
})

function canModifyComment(c) {
  if (!auth.user) return false
  return auth.user.id === c.authorId || isAdmin.value
}

async function load() {
  loading.value = true
  error.value = null
  try {
    post.value = await boardApi.get(postId)
  } catch (e) {
    error.value = e.response?.data?.message || '게시글을 불러오지 못했습니다.'
  } finally {
    loading.value = false
  }
}

async function removePost() {
  if (!(await dialog.confirm('이 게시글을 삭제하시겠습니까?', { title: '게시글 삭제', danger: true }))) return
  try {
    await boardApi.remove(postId)
    router.replace(`/board/${category.value}`)
  } catch (e) {
    alert(e.response?.data?.message || '삭제에 실패했습니다.')
  }
}

async function blockPost() {
  const reason = await dialog.prompt('열람 제한 사유 (선택):', { title: '열람 제한', placeholder: '사유(선택)' })
  if (reason === null) return
  try {
    await boardApi.block(postId, reason)
    await load()
  } catch (e) {
    alert(e.response?.data?.message || '처리에 실패했습니다.')
  }
}

async function unblockPost() {
  try {
    await boardApi.unblock(postId)
    await load()
  } catch (e) {
    alert(e.response?.data?.message || '처리에 실패했습니다.')
  }
}

async function addComment() {
  const content = commentText.value.trim()
  if (!content) return
  submitting.value = true
  try {
    const c = await boardApi.addComment(postId, content)
    post.value.comments.push(c)
    commentText.value = ''
  } catch (e) {
    alert(e.response?.data?.message || '댓글 등록에 실패했습니다.')
  } finally {
    submitting.value = false
  }
}

async function removeComment(c) {
  if (!(await dialog.confirm('댓글을 삭제하시겠습니까?', { title: '댓글 삭제', danger: true }))) return
  try {
    await boardApi.removeComment(c.id)
    post.value.comments = post.value.comments.filter((x) => x.id !== c.id)
  } catch (e) {
    alert(e.response?.data?.message || '삭제에 실패했습니다.')
  }
}

onMounted(load)
</script>

<template>
  <section class="detail">
    <p v-if="error" class="msg error">{{ error }}</p>
    <p v-if="loading" class="msg">불러오는 중...</p>

    <article v-if="post">
      <header class="post-head">
        <h1><span v-if="post.notice" class="notice-badge">공지</span>{{ post.title }}</h1>
        <div class="meta">
          <span>{{ post.authorName }}</span>
          <span>· {{ formatRelative(post.createdAt) }}</span>
          <span>· 조회 {{ post.viewCount }}</span>
        </div>
      </header>

      <!-- 관리자에게: 제한 상태 배너 -->
      <div v-if="post.blocked && isAdmin" class="admin-banner">
        🚫 열람 제한된 글입니다 (관리자만 열람)
        <span v-if="post.blockReason">— 사유: {{ post.blockReason }}</span>
      </div>

      <!-- 비관리자 제한 메시지 -->
      <div v-if="restricted" class="restricted">
        🚫 관리자에 의해 열람이 제한된 게시글입니다.
      </div>

      <MarkdownViewer v-else :content="post.content" class="content" />

      <!-- 태그 (본문 아래) -->
      <div v-if="!restricted && post.tags?.length" class="tags">
        <span v-for="t in post.tags" :key="t" class="tag">{{ t }}</span>
      </div>

      <div class="actions">
        <IconBtn icon="list" title="목록" @click="router.push(`/board/${category}`)" />
        <div class="right-actions">
          <!-- 관리자 제한/해제 -->
          <button v-if="isAdmin && !post.blocked" type="button" class="warn" @click="blockPost">열람 제한</button>
          <button v-if="isAdmin && post.blocked" type="button" class="warn" @click="unblockPost">제한 해제</button>
          <!-- 작성자/관리자 수정·삭제 -->
          <template v-if="canModifyPost && !restricted">
            <IconBtn v-if="!post.blocked" icon="edit" title="수정" @click="router.push(`/board/${category}/${post.id}/edit`)" />
            <IconBtn icon="trash" title="삭제" variant="danger" @click="removePost" />
          </template>
        </div>
      </div>

      <!-- 댓글 (제한 글은 비관리자에게 숨김, 댓글 작성은 제한 글에서 불가) -->
      <section v-if="!restricted" class="comments">
        <h2>댓글 {{ post.comments.length }}</h2>

        <ul class="comment-list">
          <li v-for="c in post.comments" :key="c.id" class="comment">
            <div class="comment-head">
              <strong>{{ c.authorName }}</strong>
              <span class="comment-date">{{ formatRelative(c.createdAt) }}</span>
              <span v-if="canModifyComment(c)" class="comment-del">
                <IconBtn icon="trash" title="댓글 삭제" variant="danger" size="sm" @click="removeComment(c)" />
              </span>
            </div>
            <MarkdownViewer :content="c.content" class="comment-body" />
          </li>
        </ul>
        <p v-if="!post.comments.length" class="msg">첫 댓글을 남겨보세요.</p>

        <form v-if="!post.blocked" class="comment-form" @submit.prevent="addComment">
          <MarkdownEditor
            v-model="commentText"
            height="160px"
            initial-edit-type="wysiwyg"
            placeholder="댓글을 입력하세요"
          />
          <div class="comment-submit">
            <IconBtn icon="send" title="댓글 등록" variant="primary" type="submit" :disabled="submitting" />
          </div>
        </form>
      </section>
    </article>
  </section>
</template>

<style scoped>
.detail {
  max-width: 800px;
  margin: 0 auto;
}
.post-head {
  border: 1px solid var(--color-border);
  border-radius: 6px;
  background: var(--color-background-soft);
  padding: 1rem 1.25rem;
  margin-bottom: 1.25rem;
}
h1 {
  font-size: 1.5rem;
  margin-bottom: 0.5rem;
}
.meta {
  font-size: 0.85rem;
  color: var(--color-text);
  opacity: 0.75;
  display: flex;
  gap: 0.4rem;
  flex-wrap: wrap;
}
.tags {
  display: flex;
  gap: 0.4rem;
  flex-wrap: wrap;
  padding: 0.75rem 0 1.25rem;
  border-top: 1px solid var(--color-border);
  margin-top: 0.5rem;
}
.tag {
  font-size: 0.8rem;
  color: hsla(160, 100%, 37%, 1);
}
.admin-banner {
  background: rgba(192, 57, 43, 0.1);
  border: 1px solid #c0392b;
  color: #c0392b;
  border-radius: 4px;
  padding: 0.5rem 0.75rem;
  margin-bottom: 1rem;
  font-size: 0.9rem;
}
.restricted {
  padding: 3rem 1rem;
  text-align: center;
  color: #c0392b;
  border: 1px dashed var(--color-border);
  border-radius: 6px;
  margin-bottom: 1.5rem;
}
.content {
  white-space: pre-wrap;
  line-height: 1.7;
  min-height: 120px;
  padding: 0.5rem 0 1.5rem;
}
button {
  padding: 0.45rem 0.9rem;
  border: 1px solid var(--color-border);
  border-radius: 4px;
  background: var(--color-background-soft);
  color: var(--color-text);
  cursor: pointer;
}
button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
button.danger {
  border-color: #c0392b;
  color: #c0392b;
}
button.warn {
  border-color: #e67e22;
  color: #e67e22;
}
button.notice-btn {
  border-color: hsla(160, 100%, 37%, 1);
  color: hsla(160, 100%, 37%, 1);
}
.notice-badge {
  margin-right: 0.4rem;
  padding: 0.1rem 0.45rem;
  border-radius: 4px;
  background: hsla(160, 100%, 37%, 1);
  color: #fff;
  font-size: 0.8rem;
  font-weight: 700;
  vertical-align: middle;
}
.actions {
  display: flex;
  justify-content: space-between;
  border-top: 1px solid var(--color-border);
  padding-top: 1rem;
}
.right-actions {
  display: flex;
  gap: 0.5rem;
}
.comments {
  margin-top: 2rem;
}
.comments h2 {
  font-size: 1.1rem;
  margin-bottom: 0.75rem;
}
.comment-list {
  list-style: none;
}
.comment {
  padding: 0.75rem 0;
  border-bottom: 1px solid var(--color-border);
}
.comment-head {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.85rem;
}
.comment-date {
  opacity: 0.7;
}
.comment-del {
  margin-left: auto;
  padding: 0.15rem 0.5rem;
  font-size: 0.78rem;
}
.comment-body {
  margin-top: 0.3rem;
}
.comment-form {
  margin-top: 1rem;
}
.comment-submit {
  display: flex;
  justify-content: flex-end;
  margin-top: 0.5rem;
}
.msg {
  margin: 0.75rem 0;
}
.msg.error {
  color: #c0392b;
}
</style>
