<template>
  <PageShell title="Bulletin Board" :subtitle="pageSubtitle">
    <div class="action-bar">
      <button
        v-if="cooperativeTags.length > 0"
        type="button"
        class="drawer-btn"
        @click="showTagsDrawer = !showTagsDrawer"
      >
        Tags...
        <span v-if="activeTagFilter" class="tag-count-badge">1</span>
      </button>
      <button type="button" class="new-post-btn" @click="openNewForm">
        + New Post
      </button>
    </div>

    <div v-if="showTagsDrawer && cooperativeTags.length > 0" class="tags-drawer">
      <div class="skills-bar">
        <span class="tag-label">Filter:</span>
        <button
          v-for="tag in visibleTagOptions"
          :key="tag.slug"
          type="button"
          class="skill-tag"
          :class="{ active: activeTagFilter === tag.slug }"
          @click="toggleTagFilter(tag.slug)"
        >
          {{ tag.label || tag.name }}
        </button>
        <button
          v-if="cooperativeTags.length > 10"
          type="button"
          class="more-btn"
          @click="showAllTags = !showAllTags"
        >
          {{ showAllTags ? 'Show less' : `+${cooperativeTags.length - 10} more` }}
        </button>
      </div>
    </div>

    <div v-if="showForm" class="form-wrapper">
      <BoardPostForm
        :post="editingPost"
        :tags="cooperativeTags"
        @submit="handleSubmit"
        @cancel="closeForm"
      />
    </div>

    <ClientOnly>
      <div v-if="loading" class="loading-state">
        <p>Loading board...</p>
      </div>

      <template v-else>
        <div v-if="posts.length === 0" class="empty-state">
          <p class="empty-title">No posts yet.</p>
          <p class="empty-sub">Be the first to post.</p>
          <button type="button" class="new-post-btn" @click="openNewForm">
            + New Post
          </button>
        </div>

        <div v-else class="post-grid">
          <BoardPostCard
            v-for="post in posts"
            :key="post._id"
            :post="post"
            :channels="channels"
            :tags="cooperativeTags"
            :editable="isAuthor(post)"
            :pending-delete="pendingDeleteId === post._id"
            @edit="handleEdit"
            @delete="requestDelete"
            @confirm-delete="confirmDelete"
            @cancel-delete="cancelDelete"
          />
        </div>
      </template>

      <template #fallback>
        <div class="loading-state">
          <p>Loading board...</p>
        </div>
      </template>
    </ClientOnly>
  </PageShell>
</template>

<script setup>
definePageMeta({ middleware: ['members-auth'] })

const { memberData } = useAuth()
const { posts, loading, fetchPosts, createPost, updatePost, deletePost } = useBoardPosts()
const { channels, fetchChannels } = useBoardChannels()
const toast = useToast()

const cooperativeTags = ref([])
const showTagsDrawer = ref(false)
const showAllTags = ref(false)
const activeTagFilter = ref(null)

const showForm = ref(false)
const editingPost = ref(null)
const pendingDeleteId = ref(null)

const currentMemberId = computed(() => memberData.value?._id || null)

const pageSubtitle = computed(() => {
  const count = posts.value.length
  return `${count} post${count === 1 ? '' : 's'}`
})

const visibleTagOptions = computed(() =>
  showAllTags.value ? cooperativeTags.value : cooperativeTags.value.slice(0, 10)
)

const isAuthor = (post) => {
  if (!currentMemberId.value || !post.author) return false
  const authorId = typeof post.author === 'object' ? post.author._id : post.author
  return String(authorId) === String(currentMemberId.value)
}

const toggleTagFilter = async (slug) => {
  activeTagFilter.value = activeTagFilter.value === slug ? null : slug
  await fetchPosts(activeTagFilter.value ? { tag: activeTagFilter.value } : {})
}

const openNewForm = () => {
  editingPost.value = null
  showForm.value = true
}

const closeForm = () => {
  showForm.value = false
  editingPost.value = null
}

const handleEdit = (post) => {
  editingPost.value = post
  showForm.value = true
  if (typeof window !== 'undefined') {
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }
}

const requestDelete = (post) => {
  pendingDeleteId.value = post._id
}

const cancelDelete = () => {
  pendingDeleteId.value = null
}

const confirmDelete = async (post) => {
  try {
    await deletePost(post._id)
    pendingDeleteId.value = null
  } catch (err) {
    toast.add({
      title: 'Failed to delete post',
      description: err?.data?.message || err?.message || 'Please try again.',
      color: 'red',
    })
  }
}

const handleSubmit = async (body) => {
  try {
    if (editingPost.value) {
      await updatePost(editingPost.value._id, body)
    } else {
      await createPost(body)
    }
    closeForm()
  } catch (err) {
    toast.add({
      title: editingPost.value ? 'Failed to update post' : 'Failed to create post',
      description: err?.data?.message || err?.message || 'Please try again.',
      color: 'red',
    })
  }
}

const loadTags = async () => {
  const data = await $fetch('/api/tags')
  cooperativeTags.value = (data.tags || []).filter((t) => t.pool === 'cooperative')
}

useHead({
  title: 'Board - Ghost Guild',
  meta: [
    {
      name: 'description',
      content: 'Share what you are seeking and offering with the Ghost Guild community.',
    },
  ],
})

onMounted(async () => {
  await Promise.allSettled([loadTags(), fetchPosts(), fetchChannels()])
})
</script>

<style scoped>
.action-bar {
  padding: 12px 24px;
  border-bottom: 1px dashed var(--border);
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}

.new-post-btn {
  font-family: "Commit Mono", monospace;
  font-size: 11px;
  letter-spacing: 0.04em;
  color: var(--candle);
  background: transparent;
  border: 1px dashed var(--candle-faint);
  padding: 4px 12px;
  cursor: pointer;
  transition: all 0.15s;
}
.new-post-btn:hover {
  border-style: solid;
  background: rgba(154, 116, 32, 0.08);
}
.new-post-btn:focus-visible {
  outline: 2px dashed var(--candle);
  outline-offset: 2px;
}

/* ---- TAGS DRAWER ---- */
.drawer-btn {
  font-family: "Commit Mono", monospace;
  font-size: 11px;
  color: var(--text-dim);
  background: none;
  border: 1px dashed var(--border);
  padding: 3px 10px;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  transition: all 0.15s;
}
.drawer-btn:hover {
  border-color: var(--candle-faint);
  color: var(--text);
}
.drawer-btn:focus-visible {
  outline: 2px dashed var(--candle);
  outline-offset: 2px;
}
.tag-count-badge {
  font-size: 9px;
  background: var(--candle-faint);
  color: var(--candle);
  padding: 0 4px;
  min-width: 14px;
  text-align: center;
}
.tags-drawer {
  border-bottom: 1px dashed var(--border);
}
.skills-bar {
  padding: 12px 24px;
  display: flex;
  gap: 6px;
  align-items: center;
  flex-wrap: wrap;
}
.skills-bar .tag-label {
  font-size: 10px;
  color: var(--text-faint);
  margin-right: 4px;
  text-transform: uppercase;
  letter-spacing: 0.06em;
}
.skills-bar .skill-tag {
  font-family: "Commit Mono", monospace;
  font-size: 10px;
  color: var(--text-dim);
  padding: 2px 8px;
  border: 1px dashed var(--border);
  background: transparent;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.15s;
}
.skills-bar .skill-tag:hover {
  border-color: var(--candle-faint);
  color: var(--text);
}
.skills-bar .skill-tag.active {
  border-color: var(--candle-dim);
  border-style: solid;
  color: var(--candle);
  background: rgba(154, 116, 32, 0.08);
}
.skills-bar .skill-tag:focus-visible,
.more-btn:focus-visible {
  outline: 2px dashed var(--candle);
  outline-offset: 2px;
}
.more-btn {
  font-family: "Commit Mono", monospace;
  font-size: 10px;
  color: var(--candle);
  background: none;
  border: none;
  cursor: pointer;
  padding: 2px 4px;
}
.more-btn:hover {
  text-decoration: underline;
}

/* ---- FORM WRAPPER ---- */
.form-wrapper {
  padding: 16px 24px;
  border-bottom: 1px dashed var(--border);
  max-width: 640px;
}

/* ---- POST GRID (masonry via CSS columns) ---- */
.post-grid {
  column-count: 2;
  column-gap: 16px;
  padding: 20px 24px;
}
.post-grid > * {
  display: block;
  width: 100%;
  margin: 0 0 16px;
}
@media (min-width: 1400px) {
  .post-grid {
    column-count: 3;
  }
}

/* ---- LOADING / EMPTY ---- */
.loading-state {
  padding: 60px 24px;
  text-align: center;
  color: var(--text-faint);
  font-size: 12px;
}
.empty-state {
  padding: 60px 24px;
  text-align: center;
}
.empty-title {
  font-family: "Brygada 1918", serif;
  font-size: 20px;
  color: var(--text-dim);
  margin-bottom: 6px;
}
.empty-sub {
  font-size: 12px;
  color: var(--text-faint);
  margin-bottom: 16px;
}

/* ---- RESPONSIVE ---- */
@media (max-width: 1024px) {
  .post-grid {
    column-count: 1;
  }
}
@media (max-width: 768px) {
  .action-bar {
    padding: 12px 16px;
  }
  .skills-bar {
    padding: 10px 16px;
  }
  .post-grid,
  .form-wrapper {
    padding: 16px;
  }
}
</style>
