<template>
  <article class="board-post">
    <header class="post-header">
      <span class="post-meta">{{ typeLabel }}</span>
      <div v-if="editable && !pendingDelete" class="post-actions">
        <button type="button" class="action-btn" @click="$emit('edit', post)">Edit</button>
        <button type="button" class="action-btn danger" @click="$emit('delete', post)">Delete</button>
      </div>
      <div v-else-if="editable && pendingDelete" class="post-actions confirm">
        <span class="confirm-label">Delete?</span>
        <button type="button" class="action-btn" @click="$emit('cancel-delete', post)">Cancel</button>
        <button type="button" class="action-btn danger" @click="$emit('confirm-delete', post)">Confirm</button>
      </div>
    </header>

    <h2 class="post-title">{{ post.title }}</h2>

    <div v-if="post.seeking" class="post-block">
      <div class="block-label">Seeking</div>
      <p class="block-text">{{ post.seeking }}</p>
    </div>

    <div v-if="post.offering" class="post-block">
      <div class="block-label">Offering</div>
      <p class="block-text">{{ post.offering }}</p>
    </div>

    <p v-if="post.note" class="post-note">{{ post.note }}</p>

    <div v-if="post.tags && post.tags.length" class="post-tags">
      <span v-for="slug in post.tags" :key="slug" class="tag-pill">{{ tagLabel(slug) }}</span>
    </div>

    <footer class="post-footer">
      <div class="author">
        <img
          v-if="authorAvatar"
          :src="authorAvatar"
          :alt="post.author.name"
          class="author-avatar"
        >
        <span v-else class="author-avatar avatar-placeholder" aria-hidden="true">{{ authorInitial }}</span>
        <span class="author-name">{{ post.author ? post.author.name : 'Unknown' }}</span>
        <span v-if="slackHandle" class="slack-handle-wrap">
          <button
            type="button"
            class="slack-handle"
            :title="copied ? 'Copied!' : 'Click to copy Slack handle'"
            @click="copySlackHandle"
          >@{{ slackHandle }}</button>
          <button
            type="button"
            class="copy-link"
            :class="{ copied }"
            @click="copySlackHandle"
          >{{ copied ? 'Copied!' : 'Copy' }}</button>
        </span>
      </div>
      <a
        v-if="slackLinks.length === 1"
        :href="slackLinks[0].url"
        target="_blank"
        rel="noopener"
        class="slack-link"
      >Discuss in #{{ slackLinks[0].name }} &rarr;</a>
      <details v-else-if="slackLinks.length > 1" class="slack-menu">
        <summary class="slack-link">Discuss on Slack &#9662;</summary>
        <ul class="slack-menu-list">
          <li v-for="link in slackLinks" :key="link.id">
            <a :href="link.url" target="_blank" rel="noopener" class="slack-link">#{{ link.name }}</a>
          </li>
        </ul>
      </details>
    </footer>
  </article>
</template>

<script setup>
const props = defineProps({
  post: { type: Object, required: true },
  channels: { type: Array, default: () => [] },
  tags: { type: Array, default: () => [] },
  editable: { type: Boolean, default: false },
  pendingDelete: { type: Boolean, default: false },
})

defineEmits(['edit', 'delete', 'confirm-delete', 'cancel-delete'])

const { slackUrl } = useBoardChannels()

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

const authorAvatar = computed(() => {
  const a = props.post.author?.avatar
  if (!a) return null
  return `/ghosties/Ghost-${capitalizeAvatar(a)}.png`
})

const slackHandle = computed(() => props.post.author?.board?.slackHandle || '')

const authorInitial = computed(() => {
  const name = props.post.author?.name || ''
  return name.trim().charAt(0).toUpperCase() || '?'
})

const copied = ref(false)
const copySlackHandle = async () => {
  if (!slackHandle.value) return
  try {
    await navigator.clipboard.writeText(`@${slackHandle.value}`)
    copied.value = true
    setTimeout(() => { copied.value = false }, 1500)
  } catch {
    // clipboard unavailable
  }
}

const tagLabelMap = computed(() => {
  const map = {}
  for (const t of props.tags) map[t.slug] = t.label || t.name || t.slug
  return map
})
const tagLabel = (slug) => tagLabelMap.value[slug] || slug

const hasSeeking = computed(() => !!(props.post.seeking && props.post.seeking.trim()))
const hasOffering = computed(() => !!(props.post.offering && props.post.offering.trim()))

const typeLabel = computed(() => {
  if (hasSeeking.value && hasOffering.value) return 'SEEKING + OFFERING'
  if (hasSeeking.value) return 'SEEKING'
  if (hasOffering.value) return 'OFFERING'
  return ''
})

const slackLinks = computed(() => {
  const postTags = props.post.tags || []
  if (!postTags.length) return []
  return props.channels
    .filter((c) => {
      if (!c.slackChannelId) return false
      const slugs = c.tagSlugs || []
      return slugs.some((s) => postTags.includes(s))
    })
    .map((c) => ({
      id: c.slackChannelId,
      name: c.slackChannelName || c.name || c.slackChannelId,
      url: slackUrl(c.slackChannelId),
    }))
})
</script>

<style scoped>
.board-post {
  border: 1px dashed var(--border);
  padding: 18px 22px;
  background: var(--surface);
  break-inside: avoid;
  -webkit-column-break-inside: avoid;
  page-break-inside: avoid;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: baseline;
  gap: 12px;
  margin-bottom: 6px;
}

.post-meta {
  font-family: "Commit Mono", monospace;
  font-size: 10px;
  letter-spacing: 0.1em;
  text-transform: uppercase;
  color: var(--text-faint);
}

.post-actions {
  display: flex;
  gap: 6px;
  align-items: center;
}
.post-actions.confirm .confirm-label {
  font-size: 10px;
  letter-spacing: 0.1em;
  text-transform: uppercase;
  color: var(--ember);
  margin-right: 2px;
}
.action-btn {
  font-family: "Commit Mono", monospace;
  font-size: 10px;
  letter-spacing: 0.04em;
  padding: 3px 9px;
  border: 1px dashed var(--border);
  background: transparent;
  color: var(--text-dim);
  cursor: pointer;
  transition: all 0.12s;
}
.action-btn:hover {
  color: var(--text-bright);
  border-color: var(--border-d);
}
.action-btn.danger:hover {
  color: var(--ember);
  border-color: var(--ember);
}
.action-btn:focus-visible {
  outline: 2px dashed var(--candle);
  outline-offset: 2px;
}

.post-title {
  font-family: "Brygada 1918", serif;
  font-size: 19px;
  font-weight: 500;
  color: var(--text-bright);
  margin: 0 0 12px;
  line-height: 1.2;
}

.post-block {
  margin-bottom: 10px;
}
.block-label {
  font-size: 10px;
  letter-spacing: 0.1em;
  text-transform: uppercase;
  color: var(--text-faint);
  margin-bottom: 2px;
}
.block-text {
  font-size: 13px;
  color: var(--text);
  white-space: pre-wrap;
}

.post-note {
  font-size: 11px;
  color: var(--text-faint);
  font-style: italic;
  margin: 8px 0;
  white-space: pre-wrap;
}

.post-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin: 10px 0;
}
.tag-pill {
  display: inline-block;
  font-size: 10px;
  font-family: "Commit Mono", monospace;
  color: var(--text-dim);
  padding: 2px 8px;
  border: 1px dashed var(--border);
}

.post-footer {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
  margin-top: 14px;
  padding-top: 10px;
  border-top: 1px dashed var(--border);
}

.author {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 6px 8px;
}
.author-avatar {
  width: 20px;
  height: 20px;
  object-fit: cover;
}
.avatar-placeholder {
  background: transparent;
  border: 1px dashed var(--border);
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  color: var(--text-faint);
  font-family: "Commit Mono", monospace;
}
.author-name {
  font-size: 11px;
  color: var(--text-dim);
  font-family: "Commit Mono", monospace;
}
.slack-handle-wrap {
  display: inline-flex;
  align-items: baseline;
  gap: 6px;
}
.slack-handle {
  font-size: 11px;
  color: var(--text-faint);
  font-family: "Commit Mono", monospace;
  background: transparent;
  border: none;
  padding: 0;
  cursor: pointer;
}
.slack-handle:hover {
  color: var(--candle);
}
.slack-handle:focus-visible,
.copy-link:focus-visible {
  outline: 2px dashed var(--candle);
  outline-offset: 2px;
}
.copy-link {
  font-size: 11px;
  font-family: "Commit Mono", monospace;
  color: var(--candle);
  background: transparent;
  border: none;
  padding: 0;
  cursor: pointer;
  text-decoration: underline;
}
.copy-link:hover {
  color: var(--candle-dim);
}
.copy-link.copied {
  color: var(--candle);
  text-decoration: none;
}

.slack-menu {
  position: relative;
}
.slack-menu > summary {
  list-style: none;
  cursor: pointer;
}
.slack-menu > summary::-webkit-details-marker {
  display: none;
}
.slack-menu-list {
  position: absolute;
  right: 0;
  top: 100%;
  margin-top: 6px;
  padding: 6px 10px;
  list-style: none;
  background: var(--surface);
  border: 1px dashed var(--border);
  display: flex;
  flex-direction: column;
  gap: 4px;
  white-space: nowrap;
  z-index: 10;
}
.slack-link {
  font-size: 11px;
  font-family: "Commit Mono", monospace;
  color: var(--candle);
  text-decoration: none;
  border-bottom: 1px dashed var(--candle-faint);
}
.slack-link:hover {
  color: var(--candle-dim);
  text-decoration: none;
  border-bottom-style: solid;
}
</style>
