<template>
  <div class="page wall">
    <!-- 顶部标题（浪漫暖色渐变，与主 App 蓝色区分但不刺眼） -->
    <header class="wall-hd">
      <div class="wall-hd__row">
        <h2 class="wall-hd__title">表白墙</h2>
        <span class="wall-hd__count">{{ list.length }} 条心动</span>
      </div>
      <p class="wall-hd__sub">把心里话，勇敢说给 TA 听</p>
    </header>

    <div class="page__inner">
      <!-- 发布触发条 -->
      <button class="compose-bar" @click="openCompose">
        <span class="compose-bar__ico"><AppIcon name="heart" :size="18" /></span>
        <span class="compose-bar__ph">写下你想对 TA 说的话…</span>
        <span class="compose-bar__btn">发布</span>
      </button>

      <!-- 加载中 / 空态 -->
      <div v-if="loading" class="wall-tip">加载中…</div>
      <van-empty v-else-if="!list.length" description="还没有表白，快来发布第一条吧" />

      <!-- 表白墙列表 -->
      <div v-else class="wall-list">
        <article
          v-for="c in list"
          :key="c.id"
          class="conf"
          :style="{ background: themeAt(c.theme).bg }"
          @click="goDetail(c.id)"
        >
          <div v-if="c.to" class="conf__to" :style="{ color: themeAt(c.theme).accent }">
            致 · {{ c.to }}
          </div>
          <p class="conf__content">{{ c.content }}</p>
          <div class="conf__foot">
            <span class="conf__author">
              <span class="conf__avatar" :style="{ background: themeAt(c.theme).accent }">{{ initial(c.author) }}</span>
              <span class="conf__name">{{ c.author }}</span>
              <span class="conf__time">· {{ formatTime(c.createdAt) }}</span>
            </span>
            <span class="conf__ops">
              <span class="conf__comment">{{ c.commentCount || 0 }} 评论</span>
              <button
                class="conf__like"
                :class="{ 'is-liked': c.liked }"
                :style="c.liked ? { color: themeAt(c.theme).accent } : null"
                @click.stop="like(c)"
              >
                <AppIcon name="heart" :size="15" />
                <span>{{ c.likes }}</span>
              </button>
            </span>
          </div>
        </article>
      </div>

      <div v-if="!loading && list.length" class="tip muted">表白内容仅供娱乐 · 请文明发言</div>
    </div>

    <!-- 发布弹窗 -->
    <van-popup v-model:show="showCompose" position="bottom" round :style="{ maxHeight: '88%' }">
      <div class="sheet">
        <div class="sheet__hd">
          <span class="sheet__title">发布表白</span>
          <van-icon name="cross" class="sheet__close" @click="showCompose = false" />
        </div>

        <div class="sheet__body">
          <van-field v-model="form.to" label="致" placeholder="TA 是谁？（选填）" maxlength="20" />
          <van-field
            v-model="form.content"
            type="textarea"
            rows="4"
            maxlength="140"
            show-word-limit
            placeholder="想对 TA 说的话…"
          />
          <van-field
            v-model="form.author"
            label="署名"
            :placeholder="form.anonymous ? '已选择匿名发布' : '怎么称呼你？'"
            :disabled="form.anonymous"
            maxlength="12"
          />

          <div class="sheet__row">
            <span class="sheet__label">匿名发布</span>
            <van-switch v-model="form.anonymous" size="20px" />
          </div>

          <div class="sheet__row">
            <span class="sheet__label">卡片配色</span>
            <div class="themes">
              <button
                v-for="(t, i) in THEMES"
                :key="i"
                class="theme-dot"
                :class="{ 'is-on': form.theme === i }"
                :style="{ background: t.accent }"
                @click="form.theme = i"
              ></button>
            </div>
          </div>

          <!-- 实时预览 -->
          <div class="preview" :style="{ background: THEMES[form.theme].bg }">
            <div v-if="form.to" class="conf__to" :style="{ color: THEMES[form.theme].accent }">
              致 · {{ form.to }}
            </div>
            <p class="conf__content">{{ form.content || '这里会实时预览你的表白内容…' }}</p>
            <div class="preview__author">— {{ form.anonymous ? '匿名' : (form.author.trim() || '匿名') }}</div>
          </div>

          <p class="sheet__note">发布后需管理员审核通过才会展示在表白墙</p>
        </div>

        <div class="sheet__foot">
          <van-button block round type="primary" :loading="submitting" @click="submit">发布表白</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onActivated } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import {
  fetchConfessions,
  publishConfession,
  likeConfession,
  hasLiked,
  formatTime,
  THEMES,
  themeAt
} from '../store/wall.js'

defineOptions({ name: 'wall' })

const router = useRouter()
const list = ref([])
const loading = ref(false)
const showCompose = ref(false)
const submitting = ref(false)
const form = reactive({ to: '', content: '', author: '', anonymous: false, theme: 0 })

async function load() {
  loading.value = true
  try {
    const data = await fetchConfessions()
    list.value = data.map((c) => ({ ...c, liked: hasLiked(c.id) }))
  } catch (e) {
    showToast(e.message || '加载失败')
  } finally {
    loading.value = false
  }
}
onMounted(load)
onActivated(load)

function initial(name) {
  return (name || '匿')[0]
}
function goDetail(id) {
  router.push('/wall/' + id)
}
function openCompose() {
  showCompose.value = true
}
function resetForm() {
  form.to = ''
  form.content = ''
  form.author = ''
  form.anonymous = false
  form.theme = 0
}
async function submit() {
  if (!form.content.trim()) {
    showToast('说点什么吧～')
    return
  }
  submitting.value = true
  try {
    await publishConfession({ ...form })
    showToast('已提交，审核通过后展示')
    showCompose.value = false
    resetForm()
  } catch (e) {
    showToast(e.message || '发布失败')
  } finally {
    submitting.value = false
  }
}
async function like(c) {
  if (c.liked) {
    showToast('你已经点过啦')
    return
  }
  try {
    const likes = await likeConfession(c.id)
    c.likes = typeof likes === 'number' ? likes : c.likes + 1
    c.liked = true
  } catch (e) {
    showToast(e.message || '操作失败')
  }
}
</script>

<style scoped>
.wall {
  background: var(--brand-bg);
}

/* 顶部标题 */
.wall-hd {
  background: linear-gradient(120deg, #ff6b9d, #ff8f6b);
  padding: calc(env(safe-area-inset-top) + 16px) 16px 20px;
}
.wall-hd__row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.wall-hd__title {
  margin: 0;
  color: #fff;
  font-size: 20px;
  font-weight: 800;
}
.wall-hd__count {
  color: #fff;
  font-size: 12px;
  background: rgba(255, 255, 255, 0.24);
  padding: 3px 10px;
  border-radius: 12px;
}
.wall-hd__sub {
  margin: 8px 0 0;
  color: rgba(255, 255, 255, 0.92);
  font-size: 13px;
}

/* 发布触发条（上浮覆盖在标题底部） */
.compose-bar {
  width: 100%;
  margin-top: -12px;
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px 14px;
  border: none;
  border-radius: var(--brand-radius);
  background: var(--brand-surface);
  box-shadow: var(--brand-shadow-md);
  cursor: pointer;
}
.compose-bar__ico {
  color: #ff5c8a;
  display: inline-flex;
}
.compose-bar__ph {
  flex: 1;
  text-align: left;
  color: var(--brand-text-tertiary);
  font-size: 14px;
}
.compose-bar__btn {
  color: #fff;
  font-size: 13px;
  font-weight: 600;
  padding: 6px 16px;
  border-radius: 16px;
  background: linear-gradient(135deg, #ff6b9d, #ff8f6b);
}

.wall-tip {
  text-align: center;
  color: var(--brand-text-tertiary);
  font-size: 13px;
  padding: 40px 0;
}

/* 表白卡片 */
.wall-list {
  margin-top: 14px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.conf {
  border-radius: var(--brand-radius-lg);
  padding: 16px;
  box-shadow: var(--brand-shadow-sm);
  cursor: pointer;
}
.conf__to {
  font-size: 13px;
  font-weight: 700;
  margin-bottom: 8px;
}
.conf__content {
  margin: 0;
  color: var(--brand-text);
  font-size: 15px;
  line-height: 1.7;
  white-space: pre-wrap;
  word-break: break-word;
}
.conf__foot {
  margin-top: 14px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.conf__author {
  display: flex;
  align-items: center;
  gap: 6px;
  min-width: 0;
}
.conf__avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  color: #fff;
  font-size: 12px;
  font-weight: 700;
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 0 0 24px;
}
.conf__name {
  font-size: 13px;
  font-weight: 600;
  color: var(--brand-text-secondary);
}
.conf__time {
  font-size: 12px;
  color: var(--brand-text-tertiary);
}
.conf__ops {
  display: flex;
  align-items: center;
  gap: 10px;
}
.conf__comment {
  font-size: 12px;
  color: var(--brand-text-tertiary);
}
.conf__like {
  display: flex;
  align-items: center;
  gap: 4px;
  border: none;
  background: rgba(255, 255, 255, 0.6);
  color: var(--brand-text-tertiary);
  font-size: 13px;
  padding: 5px 10px;
  border-radius: 16px;
  cursor: pointer;
  transition: color 0.15s, transform 0.1s;
}
.conf__like.is-liked {
  font-weight: 700;
}
.conf__like:active {
  transform: scale(0.92);
}

.tip {
  text-align: center;
  font-size: 12px;
  margin-top: 20px;
}

/* 发布弹窗 */
.sheet {
  display: flex;
  flex-direction: column;
}
.sheet__hd {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 16px 10px;
}
.sheet__title {
  font-size: 17px;
  font-weight: 700;
}
.sheet__close {
  font-size: 18px;
  color: var(--brand-text-tertiary);
}
.sheet__body {
  padding: 0 4px 8px;
}
.sheet__row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
}
.sheet__label {
  font-size: 14px;
  color: var(--brand-text-secondary);
}
.themes {
  display: flex;
  gap: 10px;
}
.theme-dot {
  width: 22px;
  height: 22px;
  border-radius: 50%;
  border: 2px solid transparent;
  cursor: pointer;
  padding: 0;
}
.theme-dot.is-on {
  border-color: var(--brand-text);
  transform: scale(1.1);
}
.preview {
  margin: 6px 16px 4px;
  border-radius: var(--brand-radius);
  padding: 14px;
}
.preview__author {
  margin-top: 10px;
  text-align: right;
  font-size: 12px;
  color: var(--brand-text-secondary);
}
.sheet__note {
  margin: 8px 16px 0;
  font-size: 12px;
  color: var(--brand-text-tertiary);
  text-align: center;
}
.sheet__foot {
  padding: 12px 16px calc(env(safe-area-inset-bottom) + 14px);
}
</style>
