<template>
  <PageShell title="Board" :subtitle="pageSubtitle">
    <!-- Filter Bar -->
    <div class="filter-bar">
      <span class="filter-count">{{ filteredSuggestions.length }} connection{{ filteredSuggestions.length === 1 ? '' : 's' }}</span>
    </div>

    <!-- Tags Drawer Toggle -->
    <div v-if="ecologyTagOptions.length > 0" class="tags-drawer-toggle">
      <button type="button" class="drawer-btn" @click="showTagsDrawer = !showTagsDrawer">
        Tags...
        <span v-if="ecologyFilterTags.length > 0" class="tag-count-badge">{{ ecologyFilterTags.length }}</span>
      </button>
    </div>

    <!-- Tags Drawer -->
    <div v-if="showTagsDrawer && ecologyTagOptions.length > 0" class="tags-drawer">
      <div class="skills-bar">
        <span class="tag-label">Topics:</span>
        <button
          v-for="tag in visibleTagOptions"
          :key="tag.slug"
          type="button"
          class="skill-tag"
          :class="{ active: ecologyFilterTags.includes(tag.slug) }"
          @click="toggleTag(tag.slug)"
        >
          {{ tag.label }}
        </button>
        <button
          v-if="ecologyTagOptions.length > 10"
          type="button"
          class="more-btn"
          @click="showAllTags = !showAllTags"
        >
          {{ showAllTags ? 'Show less' : `+${ecologyTagOptions.length - 10} more` }}
        </button>
      </div>
    </div>

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

      <template v-else>
        <!-- No topics empty state -->
        <div v-if="hasNoTopics" class="empty-state">
          <p class="empty-title">No topics yet</p>
          <p class="empty-sub">
            <NuxtLink to="/member/profile">Add topics to your profile</NuxtLink> to find connections.
          </p>
        </div>

        <!-- Suggestions grid -->
        <div v-else-if="filteredSuggestions.length > 0" class="member-grid">
          <div
            v-for="suggestion in filteredSuggestions"
            :key="suggestion.member._id"
            class="member-card ecology-card"
          >
            <div class="mc-head">
              <div class="mc-avatar">
                <img
                  v-if="suggestion.member.avatar"
                  :src="`/ghosties/Ghost-${capitalize(suggestion.member.avatar)}.png`"
                  :alt="suggestion.member.name"
                  class="mc-avatar-img"
                />
                <span v-else>{{ getInitials(suggestion.member.name) }}</span>
              </div>
              <div class="mc-info">
                <div class="cc-name">
                  <NuxtLink :to="`/members/${suggestion.member._id}`">
                    {{ suggestion.member.name }}
                  </NuxtLink>
                </div>
                <div class="cc-meta">
                  <CircleBadge :circle="suggestion.member.circle || 'community'" />
                </div>
              </div>
            </div>

            <div v-if="suggestion.member.craftTags?.length" class="cc-craft-tags">
              <span
                v-for="tag in suggestion.member.craftTags.slice(0, 5)"
                :key="tag"
                class="craft-pill"
              >{{ craftTagLabel(tag) }}</span>
              <span v-if="suggestion.member.craftTags.length > 5" class="tag-overflow">+{{ suggestion.member.craftTags.length - 5 }}</span>
            </div>

            <div class="cc-matches">
              <div
                v-for="match in suggestion.matchingTags"
                :key="match.tagSlug"
                class="match-row"
              >
                <span class="match-tag">{{ ecologyTagLabel(match.tagSlug) }}</span>
                <span class="match-states">
                  <span class="match-you">You: {{ stateLabel(match.yourState) }}</span>
                  <span class="match-sep">&middot;</span>
                  <span class="match-them">They: {{ stateLabel(match.theirState) }}</span>
                </span>
              </div>
            </div>

            <div v-if="suggestion.member.slackHandle" class="cc-contact">
              <span class="cc-slack">@{{ suggestion.member.slackHandle }}</span>
              <button
                type="button"
                class="text-action"
                @click="copyHandle(suggestion.member.slackHandle)"
              >
                {{ copiedHandle === suggestion.member.slackHandle ? 'Copied!' : 'Copy' }}
              </button>
            </div>
          </div>
        </div>

        <!-- No matches -->
        <div v-else class="empty-state">
          <p class="empty-title">No matches yet</p>
          <p class="empty-sub">
            Add cooperative topics to your
            <NuxtLink to="/member/profile">profile</NuxtLink>
            to find members with shared interests.
          </p>
        </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 { getSuggestions } = useBoard()
const { trackGoal, isComplete } = useOnboarding()

// ---- State ----
const suggestions = ref([])
const loading = ref(false)
const ecologyTagOptions = ref([])
const ecologyFilterTags = ref([])
const copiedHandle = ref(null)
const showAllTags = ref(false)
const showTagsDrawer = ref(false)
const craftTagOptions = ref([])
const cooperativeTagOptions = ref([])

// ---- Helpers ----
const stateLabels = {
  help: 'Can help',
  interested: 'Interested',
  seeking: 'Need help',
}
const stateLabel = (state) => stateLabels[state] || state || ''

const craftTagLabel = (slug) => {
  const found = craftTagOptions.value.find((t) => t.slug === slug)
  return found ? found.label : slug
}

const ecologyTagLabel = (slug) => {
  const found = ecologyTagOptions.value.find((t) => t.slug === slug)
  if (found) return found.label
  const fallback = cooperativeTagOptions.value.find((t) => t.slug === slug)
  return fallback ? fallback.label : slug
}

const getInitials = (name) => {
  if (!name) return '?'
  return name
    .split(' ')
    .map((w) => w[0])
    .join('')
    .toUpperCase()
    .slice(0, 2)
}

const capitalize = (str) => {
  if (!str) return ''
  return str
    .split('-')
    .map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
    .join('-')
}

// ---- Computed ----
const visibleTagOptions = computed(() =>
  showAllTags.value ? ecologyTagOptions.value : ecologyTagOptions.value.slice(0, 10)
)

const hasNoTopics = computed(() => {
  if (!memberData.value) return false
  const topics = memberData.value?.board?.topics
  return !topics || topics.length === 0
})

const filteredSuggestions = computed(() => {
  if (ecologyFilterTags.value.length === 0) return suggestions.value
  return suggestions.value.filter((s) =>
    s.matchingTags.some((m) => ecologyFilterTags.value.includes(m.tagSlug))
  )
})

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

// ---- Tag toggle ----
const toggleTag = (slug) => {
  const idx = ecologyFilterTags.value.indexOf(slug)
  if (idx > -1) {
    ecologyFilterTags.value.splice(idx, 1)
  } else {
    ecologyFilterTags.value.push(slug)
  }
}

// ---- Load tags ----
const loadTagOptions = async () => {
  try {
    const data = await $fetch('/api/tags')
    const tags = data.tags || []
    craftTagOptions.value = tags
      .filter((t) => t.pool === 'craft')
      .map((t) => ({ slug: t.slug, label: t.label }))
    cooperativeTagOptions.value = tags
      .filter((t) => t.pool === 'cooperative')
      .map((t) => ({ slug: t.slug, label: t.label }))
  } catch (error) {
    console.error('Failed to load tags:', error)
  }
}

// ---- Load suggestions ----
const loadBoard = async () => {
  loading.value = true
  try {
    const data = await getSuggestions()
    suggestions.value = data.suggestions || []

    // Build ecology tag options from user's own topics
    const allCoopTags = cooperativeTagOptions.value
    const myTopicSlugs = (memberData.value?.board?.topics || []).map((t) => t.tagSlug)
    ecologyTagOptions.value = myTopicSlugs.length
      ? allCoopTags.filter((t) => myTopicSlugs.includes(t.slug))
      : allCoopTags
  } catch (error) {
    console.error('Failed to load board:', error)
    suggestions.value = []
  } finally {
    loading.value = false
  }
}

// ---- Clipboard ----
let copyTimer = null
const copyHandle = async (handle) => {
  try {
    await navigator.clipboard.writeText(`@${handle}`)
    copiedHandle.value = handle
    if (copyTimer) clearTimeout(copyTimer)
    copyTimer = setTimeout(() => {
      copiedHandle.value = null
      copyTimer = null
    }, 1500)
  } catch (error) {
    console.error('Clipboard write failed:', error)
  }
}

onBeforeUnmount(() => {
  if (copyTimer) clearTimeout(copyTimer)
})

// ---- Head ----
useHead({
  title: 'Board - Ghost Guild',
  meta: [
    {
      name: 'description',
      content: 'Find Ghost Guild members who share your cooperative interests and reach out on Slack.',
    },
  ],
})

// ---- Init ----
onMounted(async () => {
  if (!isComplete.value) {
    trackGoal('boardPageVisited')
  }
  await loadTagOptions()
  await loadBoard()
})
</script>

<style scoped>
/* ---- FILTER BAR ---- */
.filter-bar {
  padding: 16px 24px;
  border-bottom: 1px dashed var(--border);
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-count {
  font-size: 11px;
  color: var(--text-faint);
}

/* ---- TAGS DRAWER ---- */
.tags-drawer-toggle {
  padding: 8px 24px;
  border-bottom: 1px dashed var(--border);
}

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

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

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

/* ---- LOADING ---- */
.loading-state {
  padding: 60px 24px;
  text-align: center;
  color: var(--text-faint);
  font-size: 12px;
}

/* ---- MEMBER GRID ---- */
.member-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 0;
}

.member-card {
  padding: 16px 20px;
  border-bottom: 1px dashed var(--border);
  border-right: 1px dashed var(--border);
  transition: background 0.15s;
}
.member-card:hover {
  background: var(--surface);
}
.member-card:nth-child(2n) {
  border-right: none;
}

/* ---- CARD LAYOUT ---- */
.mc-head {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 6px;
}

.mc-avatar {
  width: 32px;
  height: 32px;
  background: var(--surface);
  border: 1px dashed var(--border);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 11px;
  color: var(--text-faint);
  flex-shrink: 0;
  overflow: hidden;
}

.mc-avatar-img {
  width: 28px;
  height: 28px;
  object-fit: contain;
}

.mc-info {
  min-width: 0;
}

.cc-name {
  font-size: 13px;
  font-weight: 600;
  color: var(--text-bright);
}
.cc-name a {
  color: var(--text-bright);
  text-decoration: none;
}
.cc-name a:hover {
  color: var(--candle);
  text-decoration: underline;
}

.cc-meta {
  font-size: 11px;
  color: var(--text-dim);
  display: flex;
  align-items: center;
  gap: 6px;
  flex-wrap: wrap;
  margin-top: 1px;
}

.cc-craft-tags {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
  margin: 6px 0;
}

.craft-pill {
  font-size: 10px;
  color: var(--text-dim);
  padding: 1px 6px;
  border: 1px dashed var(--border);
  white-space: nowrap;
}

.tag-overflow {
  font-size: 10px;
  color: var(--text-faint);
}

.cc-matches {
  margin: 8px 0;
}

.match-row {
  display: flex;
  align-items: baseline;
  gap: 8px;
  padding: 3px 0;
  font-size: 11px;
}

.match-tag {
  color: var(--text);
  font-weight: 600;
  min-width: 0;
}

.match-states {
  color: var(--text-faint);
  font-size: 10px;
  display: flex;
  gap: 4px;
  align-items: baseline;
  flex-wrap: wrap;
}

.match-sep {
  color: var(--border);
}

.match-you,
.match-them {
  white-space: nowrap;
}

.cc-contact {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px dashed var(--border);
}

.cc-slack {
  font-size: 11px;
  color: var(--candle-dim);
  font-family: "Commit Mono", monospace;
}

.text-action {
  font-family: "Commit Mono", monospace;
  font-size: 11px;
  color: var(--text-faint);
  background: none;
  border: none;
  cursor: pointer;
  padding: 0;
}
.text-action:hover {
  color: var(--text);
  text-decoration: underline;
}

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

/* ---- RESPONSIVE ---- */
@media (max-width: 1024px) {
  .member-grid {
    grid-template-columns: 1fr;
  }
  .member-card {
    border-right: none;
  }
}

@media (max-width: 768px) {
  .filter-bar {
    flex-direction: column;
    align-items: stretch;
    padding: 14px 20px;
  }
  .skills-bar {
    padding: 10px 20px;
  }
  .tags-drawer-toggle {
    padding: 8px 20px;
  }
  .member-card {
    padding: 14px 16px;
  }
}
</style>
