<script setup>
import { onMounted, reactive, ref } from 'vue'
import { adminApi } from '@/api/adminApi'
import { useDialog } from '@/composables/dialog'
import { BOARDS } from '@/constants/boards'
import IconBtn from '@/components/ui/IconBtn.vue'

const dialog = useDialog()
const categories = ref([])
const loading = ref(false)
const error = ref(null)

const newCategoryName = ref('')
const newTag = reactive({}) // { [categoryId]: '입력값' }

async function load() {
  loading.value = true
  error.value = null
  try {
    const list = await adminApi.categories()
    list.forEach((c) => {
      if (!Array.isArray(c.boards)) c.boards = []
      if (newTag[c.id] === undefined) newTag[c.id] = ''
    })
    categories.value = list
  } catch (e) {
    error.value = e.response?.data?.message || '불러오지 못했습니다.'
  } finally {
    loading.value = false
  }
}

// 카테고리의 게시판 매핑 토글
function toggleBoard(cat, key) {
  const i = cat.boards.indexOf(key)
  if (i >= 0) cat.boards.splice(i, 1)
  else cat.boards.push(key)
}

async function addCategory() {
  const name = newCategoryName.value.trim()
  if (!name) return
  try {
    await adminApi.createCategory({ name, sortOrder: categories.value.length, boards: [] })
    newCategoryName.value = ''
    await load()
  } catch (e) {
    alert(e.response?.data?.message || '카테고리 추가 실패')
  }
}

async function saveCategory(cat) {
  const name = (cat.name || '').trim()
  if (!name) return
  try {
    await adminApi.updateCategory(cat.id, { name, sortOrder: cat.sortOrder, boards: cat.boards })
    alert('저장했습니다.')
    await load()
  } catch (e) {
    alert(e.response?.data?.message || '카테고리 수정 실패')
  }
}

async function removeCategory(cat) {
  if (!(await dialog.confirm(`'${cat.name}' 카테고리와 소속 태그를 모두 삭제할까요?`, { title: '카테고리 삭제', danger: true }))) return
  try {
    await adminApi.removeCategory(cat.id)
    await load()
  } catch (e) {
    alert(e.response?.data?.message || '삭제 실패')
  }
}

async function addTag(cat) {
  const name = (newTag[cat.id] || '').trim()
  if (!name) return
  try {
    await adminApi.createTag({ name, categoryId: cat.id })
    newTag[cat.id] = ''
    await load()
  } catch (e) {
    alert(e.response?.data?.message || '태그 추가 실패')
  }
}

async function removeTag(tag) {
  if (!(await dialog.confirm(`'${tag.name}' 태그를 삭제할까요?`, { title: '태그 삭제', danger: true }))) return
  try {
    await adminApi.removeTag(tag.id)
    await load()
  } catch (e) {
    alert(e.response?.data?.message || '삭제 실패')
  }
}

onMounted(load)
</script>

<template>
  <section class="tag-admin">
    <p class="page-hint">각 태그 그룹을 사용할 게시판을 지정하세요. 선택한 게시판의 글쓰기에서만 그 그룹 태그가 노출됩니다. <b>게시판을 하나도 선택하지 않으면 어디에도 노출되지 않습니다.</b></p>

    <form class="new-category" @submit.prevent="addCategory">
      <input v-model="newCategoryName" type="text" placeholder="새 카테고리 이름 (예: 게시판, 게시판2)" />
      <IconBtn icon="plus" title="카테고리 추가" variant="primary" type="submit" />
    </form>

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

    <div v-for="cat in categories" :key="cat.id" class="category-card">
      <div class="cat-head">
        <input v-model="cat.name" class="cat-name" @keyup.enter="saveCategory(cat)" />
        <IconBtn icon="check" title="저장" @click="saveCategory(cat)" />
        <IconBtn icon="trash" title="카테고리 삭제" variant="danger" @click="removeCategory(cat)" />
      </div>

      <div class="board-map">
        <span class="bm-label">사용 게시판</span>
        <label v-for="b in BOARDS" :key="b.key" class="bm-check">
          <input type="checkbox" :checked="cat.boards.includes(b.key)" @change="toggleBoard(cat, b.key)" />
          {{ b.label }}
        </label>
        <span v-if="!cat.boards.length" class="bm-none">미노출</span>
      </div>

      <div class="tag-list">
        <span v-for="t in cat.tags" :key="t.id" class="tag-chip">
          {{ t.name }}
          <button type="button" class="tag-x" @click="removeTag(t)">×</button>
        </span>
        <span v-if="!cat.tags.length" class="empty">태그 없음</span>
      </div>

      <form class="new-tag" @submit.prevent="addTag(cat)">
        <input v-model="newTag[cat.id]" type="text" placeholder="태그 추가" />
        <IconBtn icon="plus" title="태그 추가" type="submit" />
      </form>
    </div>

    <p v-if="!loading && !categories.length" class="msg">카테고리를 추가해 태그 관리를 시작하세요.</p>
  </section>
</template>

<style scoped>
.tag-admin {
  max-width: 800px;
  margin: 0 auto;
}
h1 {
  font-size: 1.5rem;
  margin-bottom: 1rem;
}
input {
  padding: 0.5rem 0.7rem;
  border: 1px solid var(--color-border);
  border-radius: 4px;
  background: var(--color-background-soft);
  color: var(--color-text);
}
button {
  padding: 0.45rem 0.85rem;
  border: 1px solid var(--color-border);
  border-radius: 4px;
  background: var(--color-background-soft);
  color: var(--color-text);
  cursor: pointer;
}
button.danger {
  border-color: #c0392b;
  color: #c0392b;
}
.page-hint {
  font-size: 0.85rem;
  opacity: 0.7;
  margin-bottom: 1rem;
  line-height: 1.5;
}
.board-map {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  flex-wrap: wrap;
  padding: 0.5rem 0 0.75rem;
  margin-bottom: 0.5rem;
  border-bottom: 1px dashed var(--color-border);
}
.bm-label {
  font-size: 0.82rem;
  font-weight: 600;
  opacity: 0.8;
}
.bm-check {
  display: inline-flex;
  align-items: center;
  gap: 0.3rem;
  font-size: 0.85rem;
  cursor: pointer;
}
.bm-check input {
  width: auto;
  cursor: pointer;
}
.bm-none {
  font-size: 0.78rem;
  color: #c0392b;
  opacity: 0.8;
}
.new-category {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 1.5rem;
}
.new-category input {
  flex: 1;
}
.category-card {
  border: 1px solid var(--color-border);
  border-radius: 6px;
  padding: 1rem;
  margin-bottom: 1rem;
}
.cat-head {
  display: flex;
  gap: 0.5rem;
  align-items: center;
  margin-bottom: 0.75rem;
}
.cat-name {
  flex: 1;
  font-weight: 600;
}
.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 0.4rem;
  margin-bottom: 0.75rem;
  min-height: 1.8rem;
}
.tag-chip {
  display: inline-flex;
  align-items: center;
  gap: 0.25rem;
  padding: 0.25rem 0.55rem;
  border: 1px solid var(--color-border);
  border-radius: 999px;
  font-size: 0.85rem;
}
.tag-x {
  border: 0;
  background: transparent;
  color: #c0392b;
  cursor: pointer;
  padding: 0 0.1rem;
  font-size: 1rem;
  line-height: 1;
}
.empty {
  font-size: 0.85rem;
  opacity: 0.6;
}
.new-tag {
  display: flex;
  gap: 0.5rem;
}
.new-tag input {
  flex: 1;
}
.msg {
  margin: 0.75rem 0;
}
.msg.error {
  color: #c0392b;
}
</style>
