<template>
  <PageShell title="Members">
    <!-- Filter Bar -->
    <div class="filter-bar">
      <input
        v-model="searchQuery"
        type="text"
        class="filter-search"
        placeholder="Search members..."
        @input="debouncedSearch"
      >
      <USelectMenu
        v-model="selectedCircle"
        :items="circleOptions"
        value-key="value"
        :search-input="false"
        class="zine-select circle-select"
        :ui="{
          content: 'tz-content',
          item: 'tz-item',
        }"
        @update:model-value="loadMembers"
      />
      <button
        v-if="craftTagOptions.length > 0"
        type="button"
        class="drawer-btn"
        @click="showTagsDrawer = !showTagsDrawer"
      >
        Tags...
        <span v-if="directoryCraftTags.length > 0" class="tag-count-badge">{{ directoryCraftTags.length }}</span>
      </button>
    </div>

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

    <!-- Active Filters -->
    <div v-if="hasActiveFilters" class="active-filters">
      <span class="af-label">Active filters:</span>
      <span v-if="selectedCircle && selectedCircle !== 'all'" class="af-tag">
        {{ circleLabels[selectedCircle] }}
        <button type="button" @click="clearCircleFilter">&times;</button>
      </span>
      <span v-for="slug in directoryCraftTags" :key="'c-' + slug" class="af-tag">
        {{ craftTagLabel(slug) }}
        <button type="button" @click="toggleDirectoryCraftTag(slug)">&times;</button>
      </span>
      <button
        v-if="hasActiveFilters"
        type="button"
        class="clear-all-btn"
        @click="clearAllFilters"
      >
        Clear all
      </button>
    </div>

    <!-- DIRECTORY -->
    <div v-if="loading && !members.length" class="loading-state">
      <p>Loading members...</p>
    </div>

    <div v-else-if="members.length > 0" class="member-grid">
      <div v-for="member in members" :key="member._id" class="member-card">
        <div class="mc-head">
          <div class="mc-avatar">
            <img
              v-if="member.avatar"
              :src="`/ghosties/Ghost-${capitalize(member.avatar)}.png`"
              :alt="member.name"
              class="mc-avatar-img"
            >
            <span v-else>{{ getInitials(member.name) }}</span>
          </div>
          <div class="mc-info">
            <div class="mc-name">
              <NuxtLink :to="`/members/${member._id}`">{{ member.name }}</NuxtLink>
              <span v-if="member.pronouns" class="mc-pronouns">{{ member.pronouns }}</span>
            </div>
            <div class="mc-meta">
              <CircleBadge :circle="member.circle" :label="circleLabels[member.circle]" />
              <template v-if="member.studio">
                <span class="sep">&middot;</span>
                {{ member.studio }}
              </template>
            </div>
          </div>
        </div>

        <div
          v-if="member.bio"
          class="mc-bio"
          v-html="renderMarkdown(member.bio)"
        />

        <div v-if="member.craftTags?.length > 0" class="mc-tags">
          <span class="tag-label">Craft:</span>
          <span
            v-for="tag in member.craftTags.slice(0, 3)"
            :key="tag"
            class="skill-tag"
          >{{ craftTagLabel(tag) }}</span>
          <span v-if="member.craftTags.length > 3" class="tag-overflow">+{{ member.craftTags.length - 3 }} more</span>
        </div>
      </div>
    </div>

    <div v-else class="empty-state">
      <p class="empty-title">No members found</p>
      <p class="empty-sub">Try adjusting your search or filters</p>
      <button type="button" class="btn" @click="clearAllFilters">Clear Filters</button>
    </div>

    <div v-if="members.length > 0" class="load-more">
      <span>Showing {{ members.length }} of {{ totalCount }} member{{ totalCount === 1 ? '' : 's' }}</span>
    </div>
  </PageShell>
</template>

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

const { render: renderMarkdown } = useMarkdown()

// ---- Directory state ----
const members = ref([])
const totalCount = ref(0)
const loading = ref(true)
const searchQuery = ref('')
const selectedCircle = ref('all')
const directoryCraftTags = ref([])
const craftTagOptions = ref([])
const showAllTags = ref(false)
const showTagsDrawer = ref(false)

// ---- Helpers ----
const circleOptions = [
  { label: 'All Circles', value: 'all' },
  { label: 'Community', value: 'community' },
  { label: 'Founder', value: 'founder' },
  { label: 'Practitioner', value: 'practitioner' },
]

const circleLabels = {
  community: 'Community',
  founder: 'Founder',
  practitioner: 'Practitioner',
}

const craftTagLabel = (slug) => {
  const found = craftTagOptions.value.find((t) => t.slug === slug)
  return found ? found.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 ? craftTagOptions.value : craftTagOptions.value.slice(0, 10)
)

const hasActiveFilters = computed(() =>
  (selectedCircle.value && selectedCircle.value !== 'all') ||
  directoryCraftTags.value.length > 0
)

// ---- Load members ----
const loadMembers = async () => {
  loading.value = true
  try {
    const params = {}
    if (searchQuery.value) params.search = searchQuery.value
    if (selectedCircle.value && selectedCircle.value !== 'all') params.circle = selectedCircle.value
    if (directoryCraftTags.value.length === 1) params.craftTag = directoryCraftTags.value[0]

    const data = await $fetch('/api/members/directory', { params })
    members.value = data.members || []
    totalCount.value = data.totalCount || 0

    if (data.filters?.craftTags && craftTagOptions.value.length === 0) {
      craftTagOptions.value = data.filters.craftTags
    }
  } catch (error) {
    console.error('Failed to load members:', error)
    members.value = []
    totalCount.value = 0
  } finally {
    loading.value = false
  }
}

// ---- Load tag options ----
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 }))
  } catch (error) {
    console.error('Failed to load tags:', error)
  }
}

// ---- Filter helpers ----
let searchTimeout
const debouncedSearch = () => {
  clearTimeout(searchTimeout)
  searchTimeout = setTimeout(() => {
    loadMembers()
  }, 300)
}

const toggleDirectoryCraftTag = (slug) => {
  const idx = directoryCraftTags.value.indexOf(slug)
  if (idx > -1) {
    directoryCraftTags.value.splice(idx, 1)
  } else {
    directoryCraftTags.value = [slug]
  }
  loadMembers()
}

const clearCircleFilter = () => {
  selectedCircle.value = 'all'
  loadMembers()
}

const clearAllFilters = () => {
  searchQuery.value = ''
  selectedCircle.value = 'all'
  directoryCraftTags.value = []
  showTagsDrawer.value = false
  loadMembers()
}

onBeforeUnmount(() => {
  clearTimeout(searchTimeout)
})

// ---- useHead ----
useHead({
  title: 'Member Directory - Ghost Guild',
  meta: [
    {
      name: 'description',
      content: 'Connect with members of the Ghost Guild community - game developers, founders, and practitioners building solidarity economy studios.',
    },
  ],
})

// ---- Init ----
onMounted(async () => {
  await loadTagOptions()
  await loadMembers()
})
</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-search {
  font-family: "Commit Mono", monospace;
  font-size: 12px;
  padding: 5px 12px;
  border: 1px dashed var(--border);
  background: transparent;
  color: var(--text);
  outline: none;
  min-width: 180px;
  transition: border-color 0.15s;
}
.filter-search::placeholder {
  color: var(--text-faint);
}
.filter-search:focus {
  border-color: var(--candle-faint);
}

/* Constrain the circle USelectMenu button width so it doesn't stretch. */
:deep(.circle-select) {
  width: auto !important;
  min-width: 150px;
}

/* ---- TAGS DRAWER ---- */
.drawer-btn {
  margin-left: auto;
  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;
}

/* ---- ACTIVE FILTERS ---- */
.active-filters {
  padding: 10px 24px;
  border-bottom: 1px dashed var(--border);
  display: flex;
  gap: 8px;
  align-items: center;
  flex-wrap: wrap;
  font-size: 11px;
}

.af-label {
  color: var(--text-faint);
}

.af-tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 2px 8px;
  border: 1px dashed var(--candle-faint);
  color: var(--candle);
  font-size: 10px;
  letter-spacing: 0.04em;
}
.af-tag button {
  background: none;
  border: none;
  color: var(--candle);
  cursor: pointer;
  font-size: 13px;
  line-height: 1;
  padding: 0 0 0 2px;
}
.af-tag button:hover {
  color: var(--ember);
}

.clear-all-btn {
  font-family: "Commit Mono", monospace;
  font-size: 10px;
  color: var(--candle);
  background: none;
  border: none;
  cursor: pointer;
  padding: 0;
}
.clear-all-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;
}

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

.mc-avatar {
  width: 32px;
  height: 32px;
  background: transparent;
  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;
}

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

.mc-pronouns {
  font-size: 11px;
  color: var(--text-faint);
  margin-left: 4px;
  font-weight: 400;
}

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

.mc-bio {
  font-size: 12px;
  color: var(--text-dim);
  line-height: 1.6;
  margin: 8px 0;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.mc-bio :deep(p) {
  margin: 0;
}

.mc-tags {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
  align-items: center;
  margin-top: 6px;
}
.mc-tags .tag-label {
  font-size: 10px;
  color: var(--text-faint);
  margin-right: 2px;
}

.mc-tags .skill-tag {
  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);
}

/* ---- LOAD MORE ---- */
.load-more {
  padding: 20px 24px;
  border-bottom: 1px dashed var(--border);
  font-size: 12px;
  color: var(--text-faint);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* ---- 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;
  }
  .drawer-btn {
    margin-left: 0;
  }
  .skills-bar {
    padding: 10px 20px;
  }
  .active-filters {
    padding: 8px 20px;
  }
  .member-card {
    padding: 14px 16px;
  }
}

@media (max-width: 375px) {
  .filter-bar {
    padding: 12px 16px;
    gap: 8px;
    flex-direction: row;
    flex-wrap: wrap;
  }
  .filter-search {
    flex: 1 1 auto;
    min-width: 0;
  }
}
</style>
