<template>
  <PageShell
    :title="viewMode === 'ecology' ? 'Community Ecology' : 'Members'"
    :subtitle="pageSubtitle"
  >
    <!-- Filter Bar -->
    <div class="filter-bar">
      <div class="view-toggle">
        <button
          type="button"
          class="toggle-btn"
          :class="{ active: viewMode === 'directory' }"
          @click="setViewMode('directory')"
        >
          Directory
        </button>
        <button
          type="button"
          class="toggle-btn"
          :class="{ active: viewMode === 'ecology' }"
          @click="handleEcologyToggle"
        >
          <template v-if="!isAuthenticated">
            <svg width="10" height="12" viewBox="0 0 10 12" fill="none" aria-label="Members only" class="lock-icon">
              <rect x="0.5" y="5" width="9" height="6.5" rx="0" stroke="currentColor" stroke-width="1"/>
              <path d="M2.5 5V3.5a2.5 2.5 0 015 0V5" stroke="currentColor" stroke-width="1" fill="none"/>
            </svg>
          </template>
          Ecology
        </button>
      </div>

      <template v-if="viewMode === 'directory'">
        <input
          v-model="searchQuery"
          type="text"
          class="filter-search"
          placeholder="Search members..."
          @input="debouncedSearch"
        />
        <select
          v-model="selectedCircle"
          class="filter-select"
          @change="loadMembers"
        >
          <option
            v-for="opt in circleOptions"
            :key="opt.value"
            :value="opt.value"
          >
            {{ opt.label }}
          </option>
        </select>
        <label class="filter-toggle">
          <input
            type="checkbox"
            :checked="peerSupportFilter === 'true'"
            @change="togglePeerSupport"
          />
          Offering support
        </label>
        <span class="filter-count">Showing {{ totalCount }} member{{ totalCount === 1 ? '' : 's' }} across 3 circles</span>
      </template>

      <template v-if="viewMode === 'ecology'">
        <span class="filter-count ecology-count">{{ suggestions.length }} connection{{ suggestions.length === 1 ? '' : 's' }}</span>
      </template>
    </div>

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

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

    <!-- Active Filters (directory only) -->
    <div v-if="viewMode === 'directory' && 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-if="peerSupportFilter === 'true'" class="af-tag">
        Offering Support
        <button type="button" @click="clearPeerSupportFilter">&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>

    <!-- Public CTA (unauthenticated) -->
    <div v-if="!isAuthenticated" class="public-cta">
      <p>Join Ghost Guild to see the full directory and find collaborators</p>
      <NuxtLink to="/join" class="btn btn-primary">Join Ghost Guild</NuxtLink>
    </div>

    <!-- DIRECTORY MODE -->
    <template v-if="viewMode === '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">
                <span class="badge" :class="member.circle">{{ circleLabels[member.circle] }}</span>
                <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>

          <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, 5)"
              :key="tag"
              class="skill-tag"
            >{{ craftTagLabel(tag) }}</span>
            <span v-if="member.craftTags.length > 5" class="tag-overflow">+{{ member.craftTags.length - 5 }}</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>
    </template>

    <!-- ECOLOGY MODE -->
    <template v-if="viewMode === 'ecology'">
      <ClientOnly>
        <div v-if="ecologyLoading" class="loading-state">
          <p>Loading ecology...</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 ecology...</p>
          </div>
        </template>
      </ClientOnly>
    </template>

    <!-- Auth notice (unauthenticated, has results) -->
    <div v-if="!isAuthenticated && members.length > 0" class="auth-notice">
      <p>Some member information is visible to members only.</p>
      <div class="auth-actions">
        <button
          type="button"
          class="btn"
          @click="openLoginModal({
            title: 'Sign in to see more',
            description: 'Log in to view full member profiles',
          })"
        >
          Log In
        </button>
        <NuxtLink to="/join" class="btn btn-primary">Join Ghost Guild</NuxtLink>
      </div>
    </div>
  </PageShell>
</template>

<script setup>
const route = useRoute()
const router = useRouter()
const { isAuthenticated, memberData } = useAuth()
const { openLoginModal } = useLoginModal()
const { render: renderMarkdown } = useMarkdown()
const { getSuggestions } = useEcology()
const { trackGoal, isComplete } = useOnboarding()

// ---- View mode (URL-driven) ----
const viewMode = ref(route.query.view === 'ecology' ? 'ecology' : 'directory')

watch(viewMode, (val) => {
  router.replace({ query: { ...route.query, view: val === 'ecology' ? 'ecology' : undefined } })
})

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

// ---- Ecology state ----
const suggestions = ref([])
const ecologyLoading = ref(false)
const ecologyTagOptions = ref([])
const ecologyFilterTags = ref([])
const copiedHandle = ref(null)

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

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 = directoryCraftTagOptions.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
  // Fallback to directory connection tags
  const fallback = directoryConnectionTagOptions.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: tag options & active tags based on mode ----
const currentTagOptions = computed(() =>
  viewMode.value === 'ecology' ? ecologyTagOptions.value : directoryCraftTagOptions.value
)

const currentActiveTags = computed(() =>
  viewMode.value === 'ecology' ? ecologyFilterTags.value : directoryCraftTags.value
)

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

const hasNoTopics = computed(() => {
  if (!memberData.value) return false
  const topics = memberData.value?.communityEcology?.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 hasActiveFilters = computed(() =>
  (selectedCircle.value && selectedCircle.value !== 'all') ||
  peerSupportFilter.value === 'true' ||
  directoryCraftTags.value.length > 0
)

const pageSubtitle = computed(() => {
  if (viewMode.value === 'ecology') {
    const count = suggestions.value.length
    return `${count} connection${count === 1 ? '' : 's'}`
  }
  return `${totalCount.value} member${totalCount.value === 1 ? '' : 's'} across 3 circles`
})

// ---- View mode switching ----
const handleEcologyToggle = () => {
  if (!isAuthenticated.value) {
    openLoginModal({
      title: 'Sign in to explore ecology',
      description: 'Log in to find members who share your cooperative interests',
      redirectTo: '/members?view=ecology',
    })
    return
  }
  setViewMode('ecology')
}

const setViewMode = (mode) => {
  if (viewMode.value === mode) return
  // Reset all filter state
  searchQuery.value = ''
  selectedCircle.value = 'all'
  peerSupportFilter.value = 'all'
  directoryCraftTags.value = []
  ecologyFilterTags.value = []
  showTagsDrawer.value = false
  showAllTags.value = false

  viewMode.value = mode

  if (mode === 'directory') {
    loadMembers()
  } else {
    loadEcology()
  }
}

// ---- Onboarding tracking ----
watch(viewMode, (val) => {
  if (val === 'ecology' && !isComplete.value) {
    trackGoal('ecologyPageVisited')
  }
})

// ---- Directory: 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 (peerSupportFilter.value === 'true') params.peerSupport = 'true'
    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 && directoryCraftTagOptions.value.length === 0) {
      directoryCraftTagOptions.value = data.filters.craftTags
    }
    if (data.filters?.cooperativeTags && directoryConnectionTagOptions.value.length === 0) {
      directoryConnectionTagOptions.value = data.filters.cooperativeTags
    }
  } catch (error) {
    console.error('Failed to load members:', error)
    members.value = []
    totalCount.value = 0
  } finally {
    loading.value = false
  }
}

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

// ---- Ecology: load suggestions ----
const loadEcology = async () => {
  ecologyLoading.value = true
  try {
    const data = await getSuggestions()
    suggestions.value = data.suggestions || []

    // Build ecology tag options from user's own topics
    const allCoopTags = directoryConnectionTagOptions.value
    const myTopicSlugs = (memberData.value?.communityEcology?.topics || []).map((t) => t.tagSlug)
    ecologyTagOptions.value = myTopicSlugs.length
      ? allCoopTags.filter((t) => myTopicSlugs.includes(t.slug))
      : allCoopTags
  } catch (error) {
    if (error?.statusCode === 401 || error?.status === 401) {
      viewMode.value = 'directory'
      openLoginModal({
        title: 'Session expired',
        description: 'Please sign in again to view ecology',
        redirectTo: '/members?view=ecology',
      })
    } else {
      console.error('Failed to load ecology:', error)
    }
    suggestions.value = []
  } finally {
    ecologyLoading.value = false
  }
}

// ---- Filter helpers ----
const togglePeerSupport = (e) => {
  peerSupportFilter.value = e.target.checked ? 'true' : 'all'
  loadMembers()
}

let searchTimeout
const debouncedSearch = () => {
  clearTimeout(searchTimeout)
  searchTimeout = setTimeout(() => {
    loadMembers()
  }, 300)
}

const toggleTag = (slug) => {
  if (viewMode.value === 'ecology') {
    const idx = ecologyFilterTags.value.indexOf(slug)
    if (idx > -1) {
      ecologyFilterTags.value.splice(idx, 1)
    } else {
      ecologyFilterTags.value.push(slug)
    }
  } else {
    toggleDirectoryCraftTag(slug)
  }
}

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 clearPeerSupportFilter = () => {
  peerSupportFilter.value = 'all'
  loadMembers()
}

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

// ---- 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)
  clearTimeout(searchTimeout)
})

// ---- useHead (reactive) ----
useHead(computed(() => ({
  title: viewMode.value === 'ecology'
    ? 'Community Ecology - Ghost Guild'
    : 'Member Directory - Ghost Guild',
  meta: [
    {
      name: 'description',
      content: viewMode.value === 'ecology'
        ? 'Find Ghost Guild members who share your cooperative interests and reach out on Slack.'
        : 'Connect with members of the Ghost Guild community - game developers, founders, and practitioners building solidarity economy studios.',
    },
  ],
})))

// ---- Init ----
onMounted(async () => {
  if (route.query.peerSupport === 'true') {
    peerSupportFilter.value = 'true'
  }

  await loadTagOptions()

  if (viewMode.value === 'ecology' && isAuthenticated.value) {
    await Promise.all([loadMembers(), loadEcology()])
  } else {
    if (viewMode.value === 'ecology' && !isAuthenticated.value) {
      viewMode.value = 'directory'
    }
    await loadMembers()
  }
})
</script>

<style scoped>
/* ---- VIEW TOGGLE ---- */
.view-toggle {
  display: flex;
  border: 1px dashed var(--border);
  flex-shrink: 0;
}

.toggle-btn {
  font-family: "Commit Mono", monospace;
  font-size: 11px;
  padding: 4px 12px;
  background: transparent;
  border: none;
  color: var(--text-dim);
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: all 0.15s;
}
.toggle-btn:not(:first-child) {
  border-left: 1px dashed var(--border);
}
.toggle-btn.active {
  background: var(--surface);
  color: var(--candle);
}
.toggle-btn:hover:not(.active) {
  color: var(--text);
}

.lock-icon {
  width: 10px;
  height: 12px;
  color: var(--text-faint);
}

/* ---- 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);
}

.filter-select {
  font-family: "Commit Mono", monospace;
  font-size: 11px;
  padding: 5px 10px;
  border: 1px dashed var(--border);
  background: transparent;
  color: var(--text-dim);
  cursor: pointer;
  outline: none;
  -webkit-appearance: none;
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg width='10' height='6' viewBox='0 0 10 6' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M1 1L5 5L9 1' stroke='%238a7e6a' stroke-width='1.2'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 8px center;
  padding-right: 26px;
}
.filter-select:focus {
  border-color: var(--candle-faint);
}

.filter-toggle {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 11px;
  color: var(--text-dim);
  cursor: pointer;
}
.filter-toggle input {
  accent-color: var(--candle-dim);
}

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

.ecology-count {
  margin-left: 0;
}

/* ---- 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;
}

/* ---- 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;
}

/* ---- PUBLIC CTA ---- */
.public-cta {
  padding: 24px;
  border-bottom: 1px dashed var(--border);
  text-align: center;
}
.public-cta p {
  font-size: 12px;
  color: var(--text-dim);
  margin-bottom: 12px;
}

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

/* ---- MEMBER GRID (shared) ---- */
.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: 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;
}

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

/* ---- ECOLOGY CARD ---- */
.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;
}

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

/* ---- 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);
}

/* ---- AUTH NOTICE ---- */
.auth-notice {
  padding: 24px;
  margin: 20px 24px;
  border: 1px dashed var(--candle-faint);
  text-align: center;
}
.auth-notice p {
  font-size: 12px;
  color: var(--text-dim);
  margin-bottom: 12px;
}
.auth-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
}

/* ---- 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;
  }
  .filter-count {
    margin-left: 0;
  }
  .skills-bar {
    padding: 10px 20px;
  }
  .tags-drawer-toggle {
    padding: 8px 20px;
  }
  .active-filters {
    padding: 8px 20px;
  }
  .member-card {
    padding: 14px 16px;
  }
  .auth-notice {
    margin: 16px;
  }
  .public-cta {
    padding: 20px 16px;
  }
}

@media (max-width: 375px) {
  .filter-bar {
    padding: 12px 16px;
    gap: 8px;
  }
  .view-toggle {
    width: 100%;
  }
  .toggle-btn {
    flex: 1;
    justify-content: center;
  }
  .filter-search {
    width: 100%;
    min-width: 0;
  }
  .filter-select {
    flex: 1;
  }
  .filter-toggle {
    flex: 1;
  }
}
</style>
