<template>
  <PageShell
    title="Community Ecology"
    subtitle="Find members who share your cooperative interests"
  >
    <ClientOnly>
      <div v-if="loading" class="loading-state">
        <p>Loading ecology...</p>
      </div>

      <template v-else>
        <div v-if="tagOptions.length > 0" class="filter-bar">
          <select
            v-model="filterTag"
            class="filter-select"
            @change="loadSuggestions"
          >
            <option value="">All topics</option>
            <option v-for="tag in tagOptions" :key="tag.slug" :value="tag.slug">
              {{ tag.label }}
            </option>
          </select>
        </div>

        <div class="connections-section">
          <div class="section-label">Suggested Matches</div>

          <div v-if="suggestions.length > 0" class="connection-grid">
            <div
              v-for="suggestion in suggestions"
              :key="suggestion.member._id"
              class="connection-card"
            >
              <div class="cc-head">
                <div class="cc-avatar">
                  <img
                    v-if="suggestion.member.avatar"
                    :src="`/ghosties/Ghost-${capitalize(suggestion.member.avatar)}.png`"
                    :alt="suggestion.member.name"
                    class="cc-avatar-img"
                  />
                  <span v-else>{{ getInitials(suggestion.member.name) }}</span>
                </div>
                <div class="cc-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>
              </div>

              <div class="cc-matches">
                <div
                  v-for="match in suggestion.matchingTags"
                  :key="match.tagSlug"
                  class="match-row"
                >
                  <span class="match-tag">{{ cooperativeTagLabel(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>

          <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>
        </div>
      </template>

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

<script setup>
definePageMeta({ middleware: 'auth' })

const { getSuggestions } = useEcology()

const loading = ref(true)
const suggestions = ref([])
const filterTag = ref('')
const tagOptions = ref([])
const craftTagOptions = ref([])
const copiedHandle = ref(null)

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

const cooperativeTagLabel = (slug) => {
  const found = tagOptions.value.find((t) => t.slug === slug)
  return found ? found.label : slug
}
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('-')
}

const loadSuggestions = async () => {
  try {
    const params = {}
    if (filterTag.value) params.tag = filterTag.value
    const data = await getSuggestions(params)
    suggestions.value = data.suggestions || []
  } catch (error) {
    console.error('Failed to load suggestions:', error)
    suggestions.value = []
  }
}

const { memberData } = useAuth()

const loadTags = async () => {
  try {
    const data = await $fetch('/api/tags')
    const tags = data.tags || []
    const cooperativeTags = tags
      .filter((t) => t.pool === 'cooperative')
      .map((t) => ({ slug: t.slug, label: t.label }))
    craftTagOptions.value = tags
      .filter((t) => t.pool === 'craft')
      .map((t) => ({ slug: t.slug, label: t.label }))

    const myTopicSlugs = (memberData.value?.communityEcology?.topics || []).map(
      (t) => t.tagSlug,
    )
    tagOptions.value = myTopicSlugs.length
      ? cooperativeTags.filter((t) => myTopicSlugs.includes(t.slug))
      : cooperativeTags
  } catch (error) {
    console.error('Failed to load tags:', error)
  }
}

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

onMounted(async () => {
  loading.value = true
  try {
    await Promise.all([loadTags(), loadSuggestions()])
  } finally {
    loading.value = false
  }
})

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

<style scoped>
.loading-state {
  padding: 60px 24px;
  text-align: center;
  color: var(--text-faint);
  font-size: 12px;
}

.filter-bar {
  padding: 16px 24px;
  border-bottom: 1px dashed var(--border);
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

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

.connections-section {
  padding: 20px 24px;
  border-bottom: 1px dashed var(--border);
}

.connection-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 0;
}

.connection-card {
  padding: 16px 20px;
  border: 1px dashed var(--border);
  margin: -1px 0 0 -1px;
  transition: background 0.15s;
}
.connection-card:hover {
  background: var(--surface);
}

.cc-head {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 6px;
}

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

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

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

.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;
}
.text-action:disabled {
  opacity: 0.4;
  cursor: not-allowed;
}

.empty-state {
  padding: 32px 0;
  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);
}
.empty-sub a {
  color: var(--candle);
}

@media (max-width: 1024px) {
  .connection-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .filter-bar {
    flex-direction: column;
    align-items: stretch;
    padding: 14px 20px;
  }
  .connections-section {
    padding: 16px 20px;
  }
  .connection-card {
    padding: 14px 16px;
  }
}
</style>
