<template>
  <div class="connections-page">
    <PageHeader
      title="Connections"
      subtitle="Find members who share your cooperative interests"
    />

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

      <template v-else>
        <!-- Filter Bar -->
        <div v-if="tagOptions.length > 0 || stateOptions.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>
          <select
            v-model="filterState"
            class="filter-select"
            @change="loadSuggestions"
          >
            <option value="">All states</option>
            <option value="help">Can help</option>
            <option value="interested">Interested</option>
            <option value="seeking">Need help</option>
          </select>
        </div>

        <!-- Suggested Connections -->
        <div class="connections-section">
          <div class="section-label">Suggested Connections</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>

              <!-- Craft tags -->
              <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>

              <!-- Matching topics with state labels -->
              <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>

              <!-- Actions -->
              <div class="cc-actions">
                <button
                  class="btn btn-primary btn-sm"
                  :disabled="actionLoading === suggestion.member._id"
                  @click="handleConnect(suggestion.member._id)"
                >
                  Mark as connected
                </button>
                <button
                  class="text-action"
                  :disabled="actionLoading === suggestion.member._id"
                  @click="handleHide(suggestion.member._id)"
                >
                  Hide
                </button>
              </div>
            </div>
          </div>

          <div v-else class="empty-state">
            <p class="empty-title">No suggestions right now</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>

        <!-- Your Connections -->
        <div class="connections-section">
          <div class="section-label">Your Connections</div>

          <!-- Pending Incoming -->
          <template v-if="pendingIncoming.length > 0">
            <div class="subsection-label">Pending Incoming</div>
            <div class="connection-grid">
              <div
                v-for="conn in pendingIncoming"
                :key="conn._id"
                class="connection-card"
              >
                <div class="cc-head">
                  <div class="cc-avatar">
                    <img
                      v-if="getOtherMember(conn).avatar"
                      :src="`/ghosties/Ghost-${capitalize(getOtherMember(conn).avatar)}.png`"
                      :alt="getOtherMember(conn).name"
                      class="cc-avatar-img"
                    />
                    <span v-else>{{ getInitials(getOtherMember(conn).name) }}</span>
                  </div>
                  <div class="cc-info">
                    <div class="cc-name">
                      <NuxtLink :to="`/members/${getOtherMember(conn)._id}`">
                        {{ getOtherMember(conn).name }}
                      </NuxtLink>
                    </div>
                    <div class="cc-meta">
                      <CircleBadge :circle="getOtherMember(conn).circle || 'community'" />
                      <span class="pending-label">Wants to connect</span>
                    </div>
                  </div>
                </div>

                <div v-if="conn.matchingTags?.length" class="cc-tags-inline">
                  <span
                    v-for="mt in conn.matchingTags"
                    :key="mt.tagSlug"
                    class="craft-pill"
                  >{{ cooperativeTagLabel(mt.tagSlug) }}</span>
                </div>

                <div class="cc-actions">
                  <button
                    class="btn btn-primary btn-sm"
                    :disabled="actionLoading === conn._id"
                    @click="handleConfirm(conn._id)"
                  >
                    Confirm
                  </button>
                </div>
              </div>
            </div>
          </template>

          <!-- Pending Outgoing -->
          <template v-if="pendingOutgoing.length > 0">
            <div class="subsection-label">Pending Outgoing</div>
            <div class="connection-grid">
              <div
                v-for="conn in pendingOutgoing"
                :key="conn._id"
                class="connection-card"
              >
                <div class="cc-head">
                  <div class="cc-avatar">
                    <img
                      v-if="getOtherMember(conn).avatar"
                      :src="`/ghosties/Ghost-${capitalize(getOtherMember(conn).avatar)}.png`"
                      :alt="getOtherMember(conn).name"
                      class="cc-avatar-img"
                    />
                    <span v-else>{{ getInitials(getOtherMember(conn).name) }}</span>
                  </div>
                  <div class="cc-info">
                    <div class="cc-name">
                      <NuxtLink :to="`/members/${getOtherMember(conn)._id}`">
                        {{ getOtherMember(conn).name }}
                      </NuxtLink>
                    </div>
                    <div class="cc-meta">
                      <CircleBadge :circle="getOtherMember(conn).circle || 'community'" />
                      <span class="pending-label">Pending</span>
                    </div>
                  </div>
                </div>

                <div v-if="conn.matchingTags?.length" class="cc-tags-inline">
                  <span
                    v-for="mt in conn.matchingTags"
                    :key="mt.tagSlug"
                    class="craft-pill"
                  >{{ cooperativeTagLabel(mt.tagSlug) }}</span>
                </div>

                <div class="cc-actions">
                  <button
                    class="text-action"
                    :disabled="actionLoading === conn._id"
                    @click="handleWithdraw(conn._id)"
                  >
                    Withdraw
                  </button>
                </div>
              </div>
            </div>
          </template>

          <!-- Confirmed -->
          <template v-if="confirmed.length > 0">
            <div class="subsection-label">Connected</div>
            <div class="connection-grid">
              <div
                v-for="conn in confirmed"
                :key="conn._id"
                class="connection-card"
              >
                <div class="cc-head">
                  <div class="cc-avatar">
                    <img
                      v-if="getOtherMember(conn).avatar"
                      :src="`/ghosties/Ghost-${capitalize(getOtherMember(conn).avatar)}.png`"
                      :alt="getOtherMember(conn).name"
                      class="cc-avatar-img"
                    />
                    <span v-else>{{ getInitials(getOtherMember(conn).name) }}</span>
                  </div>
                  <div class="cc-info">
                    <div class="cc-name">
                      <NuxtLink :to="`/members/${getOtherMember(conn)._id}`">
                        {{ getOtherMember(conn).name }}
                      </NuxtLink>
                    </div>
                    <div class="cc-meta">
                      <CircleBadge :circle="getOtherMember(conn).circle || 'community'" />
                      <span
                        v-if="getSlackHandle(conn)"
                        class="cc-slack"
                      >@{{ getSlackHandle(conn) }}</span>
                    </div>
                  </div>
                </div>

                <div v-if="conn.matchingTags?.length" class="cc-tags-inline">
                  <span
                    v-for="mt in conn.matchingTags"
                    :key="mt.tagSlug"
                    class="craft-pill"
                  >{{ cooperativeTagLabel(mt.tagSlug) }}</span>
                </div>
              </div>
            </div>
          </template>

          <!-- No connections at all -->
          <div
            v-if="!confirmed.length && !pendingIncoming.length && !pendingOutgoing.length && !showHidden"
            class="empty-state"
          >
            <p class="empty-sub">
              You don't have any connections yet. Use the suggestions above to get started.
            </p>
          </div>
        </div>

        <!-- Show hidden toggle -->
        <div v-if="hiddenCount > 0" class="hidden-toggle">
          <label class="filter-toggle">
            <input
              type="checkbox"
              v-model="showHidden"
              @change="handleShowHiddenToggle"
            />
            Show {{ hiddenCount }} hidden suggestion{{ hiddenCount === 1 ? '' : 's' }}
          </label>
        </div>
      </template>

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

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

const { memberData } = useAuth()
const {
  getSuggestions,
  getMyConnections,
  requestConnection,
  confirmConnection,
  hideConnection,
  withdrawConnection,
} = useConnections()

// State
const loading = ref(true)
const actionLoading = ref(null)
const suggestions = ref([])
const confirmed = ref([])
const pendingIncoming = ref([])
const pendingOutgoing = ref([])
const filterTag = ref('')
const filterState = ref('')
const showHidden = ref(false)
const hiddenCount = ref(0)
const tagOptions = ref([])
const stateOptions = ref([])
const craftTagOptions = ref([])

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

// Tag label lookups
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
}

// Build tag options from the current member's cooperative topics
const buildTagOptions = () => {
  const topics = memberData.value?.communityConnections?.topics || []
  tagOptions.value = topics.map(t => ({
    slug: t.tagSlug,
    label: cooperativeTagLabel(t.tagSlug),
  }))
}

// Helpers
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 getOtherMember = (conn) => {
  const myId = memberData.value?._id || memberData.value?.id
  if (conn.initiator?._id === myId || conn.initiator?.id === myId) {
    return conn.recipient || {}
  }
  return conn.initiator || {}
}

const getSlackHandle = (conn) => {
  const other = getOtherMember(conn)
  return other.communityConnections?.slackHandle || null
}

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

const loadConnections = async () => {
  try {
    const data = await getMyConnections()
    confirmed.value = data.confirmed || []
    pendingOutgoing.value = data.pendingOutgoing || []
    pendingIncoming.value = data.pendingIncoming || []
  } catch (error) {
    console.error('Failed to load connections:', error)
  }
}

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 }))
    tagOptions.value = cooperativeTags
    craftTagOptions.value = tags
      .filter(t => t.pool === 'craft')
      .map(t => ({ slug: t.slug, label: t.label }))

    // Filter tag options to only member's selected topics
    const myTopicSlugs = (memberData.value?.communityConnections?.topics || [])
      .map(t => t.tagSlug)
    if (myTopicSlugs.length > 0) {
      tagOptions.value = cooperativeTags.filter(t => myTopicSlugs.includes(t.slug))
    }
  } catch (error) {
    console.error('Failed to load tags:', error)
  }
}

// Count hidden suggestions (for the toggle label)
const countHidden = async () => {
  // We don't have a dedicated hidden-count endpoint, so we track locally
  // Hidden count increments when user hides, decrements on show
  // This is approximate; it resets on page load
  hiddenCount.value = 0
}

// Actions
const handleConnect = async (memberId) => {
  actionLoading.value = memberId
  try {
    await requestConnection(memberId)
    // Remove from suggestions, refresh connections
    suggestions.value = suggestions.value.filter(s => s.member._id !== memberId)
    await loadConnections()
  } catch (error) {
    console.error('Failed to create connection:', error)
  } finally {
    actionLoading.value = null
  }
}

const handleHide = async (memberId) => {
  actionLoading.value = memberId
  try {
    // The hide endpoint requires a connection ID. For suggestions (no connection yet),
    // we create a pending connection first, then immediately hide it.
    const result = await requestConnection(memberId)
    const connId = result?.connection?._id
    if (connId) {
      await hideConnection(connId)
    }
    suggestions.value = suggestions.value.filter(s => s.member._id !== memberId)
    hiddenCount.value++
  } catch (error) {
    console.error('Failed to hide suggestion:', error)
  } finally {
    actionLoading.value = null
  }
}

const handleConfirm = async (connectionId) => {
  actionLoading.value = connectionId
  try {
    await confirmConnection(connectionId)
    await loadConnections()
  } catch (error) {
    console.error('Failed to confirm connection:', error)
  } finally {
    actionLoading.value = null
  }
}

const handleWithdraw = async (connectionId) => {
  actionLoading.value = connectionId
  try {
    await withdrawConnection(connectionId)
    await loadConnections()
    await loadSuggestions()
  } catch (error) {
    console.error('Failed to withdraw connection:', error)
  } finally {
    actionLoading.value = null
  }
}

const handleShowHiddenToggle = async () => {
  // Reload suggestions — the API excludes hidden by default
  // When showing hidden, we'd need an endpoint param; for now just reload
  await loadSuggestions()
}

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

useHead({
  title: 'Connections - Ghost Guild',
  meta: [
    {
      name: 'description',
      content: 'Find and connect with Ghost Guild members who share your cooperative interests.',
    },
  ],
})
</script>

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

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

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

.subsection-label {
  font-size: 11px;
  color: var(--text-dim);
  margin: 16px 0 8px;
}
.subsection-label:first-of-type {
  margin-top: 8px;
}

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

/* ---- CARD HEADER ---- */
.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-slack {
  font-size: 11px;
  color: var(--candle-dim);
}

.pending-label {
  font-size: 10px;
  text-transform: uppercase;
  letter-spacing: 0.04em;
  color: var(--candle-dim);
}

/* ---- CRAFT TAGS (small pills) ---- */
.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;
}

/* ---- INLINE TAGS (for confirmed/pending) ---- */
.cc-tags-inline {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
  margin: 6px 0;
}

/* ---- MATCH ROWS (suggestion cards) ---- */
.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;
}

/* ---- ACTIONS ---- */
.cc-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 10px;
}

.btn-sm {
  padding: 4px 12px;
  font-size: 11px;
}

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

/* ---- HIDDEN TOGGLE ---- */
.hidden-toggle {
  padding: 16px 24px;
  border-bottom: 1px dashed var(--border);
}

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

/* ---- RESPONSIVE ---- */
@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>
