<template>
    <view class="post-card" @tap="$emit('tap')">
        <image class="post-card__avatar" :src="post.user?.avatar || '/static/images/avatar.png'" mode="aspectFill"
            @tap.stop="$emit('avatar-tap', post.user_id)" />
        <view class="post-card__body">
            <view class="post-card__main">
                <!-- 头部：昵称·时间 + 标签 -->
                <view class="post-card__header">
                    <view class="post-card__user">
                        <text class="post-card__nickname">{{ post.user?.nickname || '匿名用户' }}</text>
                        <text class="post-card__dot">·</text>
                        <text class="post-card__time">{{ formatTime(post.create_time) }}</text>
                    </view>
                    <view class="post-card__badges">
                        <view v-if="post.is_paid" class="post-card__badge post-card__badge--paid">
                            <text>{{ post.price_points }}积分</text>
                        </view>
                        <view v-if="post.is_hot" class="post-card__badge post-card__badge--hot">
                            <text>热门</text>
                        </view>
                        <view v-if="post.is_top" class="post-card__badge post-card__badge--top">
                            <text>置顶</text>
                        </view>
                    </view>
                </view>

                <!-- 正文内容 -->
                <view class="post-card__content">
                    <text class="post-card__text"
                        :class="{ 'post-card__text--locked': post.is_paid && !post.is_unlocked }">{{ post.content_short
                            || post.content }}</text>
                </view>

                <view v-if="displayTranslatedText" class="post-card__translate">
                    <text class="post-card__translate-text">{{ displayTranslatedText }}</text>
                </view>

                <!-- 付费解锁 -->
                <view v-if="post.is_paid && !post.is_unlocked" class="post-card__unlock" @tap.stop="$emit('unlock')">
                    <text class="post-card__unlock-text">{{ post.price_points }}积分解锁全文</text>
                    <view class="post-card__unlock-btn">
                        <text>解锁</text>
                    </view>
                </view>

                <!-- 图片 -->
                <view v-if="
                    post.images &&
                    post.images.length > 0 &&
                    !(post.is_paid && !post.is_unlocked)
                " class="post-card__images" :class="{ 'post-card__images--full': isLotteryPost }">
                    <template v-if="isLotteryPost">
                        <image v-for="(img, idx) in post.images" :key="idx" class="post-card__img post-card__img--full"
                            :src="img" mode="widthFix" @tap.stop="previewImage(idx)" />
                    </template>
                    <template v-else-if="trumpSourceUrl">
                        <view class="post-card__external-cover" @tap.stop="openSourceUrl">
                            <view class="post-card__external-cover-icon">
                                <text>T</text>
                            </view>
                            <view class="post-card__external-cover-body">
                                <text class="post-card__external-cover-title">Truth Social 图片暂不可直连</text>
                                <text class="post-card__external-cover-desc">点击查看原帖</text>
                            </view>
                            <view class="post-card__external-cover-btn">
                                <text>查看原帖</text>
                            </view>
                        </view>
                    </template>
                    <template v-else>
                        <image v-for="(img, idx) in post.images.slice(0, 3)" :key="idx" class="post-card__img"
                            :src="img" mode="aspectFill" @tap.stop="previewImage(idx)" />
                        <view v-if="post.images.length > 3" class="post-card__img-more" @tap.stop="previewImage(3)">
                            <text>+{{ post.images.length - 3 }}</text>
                        </view>
                    </template>
                </view>

                <!-- 话题标签 -->
                <view v-if="post.tags && post.tags.length > 0" class="post-card__tags">
                    <view v-for="(t, i) in post.tags" :key="i" class="post-card__tag">
                        <text>#{{ t }}</text>
                    </view>
                </view>
            </view>

            <!-- 操作栏 -->
            <view class="post-card__actions">
                <view class="post-card__action" @tap.stop="$emit('view')">
                    <text class="post-card__action-icon">👁</text>
                    <text class="post-card__action-num">{{ formatCount(post.view_count) }}</text>
                </view>
                <view class="post-card__action" @tap.stop="$emit('comment')">
                    <text class="post-card__action-icon">💬</text>
                    <text class="post-card__action-num">{{ formatCount(post.comment_count) }}</text>
                </view>
                <view class="post-card__action" :class="{ 'post-card__action--active': post.is_liked }"
                    @tap.stop="$emit('like')">
                    <text class="post-card__action-icon">👍</text>
                    <text class="post-card__action-num">{{ formatCount(post.like_count) }}</text>
                </view>
                <view v-if="isLiuhePost" class="post-card__action"
                    :class="{ 'post-card__action--loading': post._ai_loading }" @tap.stop="handleAiAnalysis">
                    <text class="post-card__action-icon">🤖</text>
                    <text class="post-card__action-num">{{
                        post._ai_loading ? '…' : (aiAnalyzed ? '已分析' : 'AI')
                    }}</text>
                </view>
                <view class="post-card__action" @tap.stop="handleShareTap">
                    <text class="post-card__action-icon">↗</text>
                    <text class="post-card__action-num">{{ post.share_count ? formatCount(post.share_count) : ''
                    }}</text>
                </view>
            </view>
        </view>

        <share-popup v-if="showSharePopup" v-model:show="showSharePopup" page-type="post" :page-id="post.id"
            :path="`/packages_community/pages/post_detail?id=${post.id}`"
            :title="post.content?.substring(0, 50) || '来看看这篇帖子'" />
    </view>
</template>

<script lang="ts" setup>
import { computed, ref, watch } from 'vue'
import { translatePost } from '@/api/community'
import { getToken } from '@/utils/auth'
import SharePopup from '@/components/share-popup/share-popup.vue'

const props = defineProps<{
    post: any
}>()

const emit = defineEmits(['tap', 'unlock', 'view', 'comment', 'like', 'avatar-tap', 'ai-analysis'])

const showSharePopup = ref(false)
const handleShareTap = () => {
    showSharePopup.value = true
}

const LIUHE_TAGS = ['旧澳六合', '新澳六合']
const translatedText = ref('')
const cachedContent = ref(props.post.translated_content || '')
const isLotteryPost = computed(
    () => Array.isArray(props.post?.tags) && props.post.tags.includes('彩票')
)
const isLiuhePost = computed(() => {
    const tags = Array.isArray(props.post?.tags) ? props.post.tags : []
    return LIUHE_TAGS.some((tag) => tags.includes(tag))
})
const isTrumpPost = computed(
    () => Array.isArray(props.post?.tags) && props.post.tags.includes('特朗普')
)
const trumpSourceUrl = computed(() => {
    if (props.post?.source_url) return props.post.source_url
    const originId = props.post?.origin_id || ''
    if (!originId.startsWith('truthsocial:')) return ''
    const postId = originId.split(':')[1]
    if (!postId) return ''
    return `https://truthsocial.com/@realDonaldTrump/${postId}`
})
const displayTranslatedText = computed(() => translatedText.value || cachedContent.value || props.post?.translated_content || '')
const autoTranslateStarted = ref(false)
const aiAnalyzed = computed(() => !!displayTranslatedText.value)

const openSourceUrl = () => {
    if (!trumpSourceUrl.value) return
    uni.navigateTo({
        url: `/pages/webview/webview?url=${encodeURIComponent(trumpSourceUrl.value)}`
    })
}

const previewImage = (index: number) => {
    const images = props.post?.images || []
    if (!images.length) return
    uni.previewImage({
        urls: images,
        current: images[index] || images[0],
    })
}

const requestTranslate = async () => {
    try {
        const res = await translatePost({ post_id: props.post.id })
        if (res?.translated_content) {
            cachedContent.value = res.translated_content
            translatedText.value = res.translated_content
            return
        }
    } catch (e: any) {
    }
}

const handleAiAnalysis = () => {
    if (props.post._ai_loading) return
    if (!getToken()) {
        uni.showToast({ title: '请先登录', icon: 'none' })
        return
    }
    emit('ai-analysis', props.post)
}

watch(
    () => props.post?.translated_content,
    (value) => {
        if (value) {
            cachedContent.value = value
            translatedText.value = value
        }
    },
    { immediate: true }
)

watch(
    () => props.post?.id,
    async () => {
        autoTranslateStarted.value = false
        cachedContent.value = props.post?.translated_content || ''
        translatedText.value = props.post?.translated_content || ''
        if (!isTrumpPost.value || cachedContent.value || autoTranslateStarted.value || !props.post?.content) return
        autoTranslateStarted.value = true
        if (getToken()) {
            await requestTranslate()
        }
    },
    { immediate: true }
)

const formatTime = (ts: any) => {
    if (!ts) return ''
    let timestamp: number
    if (typeof ts === 'string') {
        timestamp = new Date(ts.replace(/-/g, '/')).getTime() / 1000
    } else {
        timestamp = ts
    }
    if (isNaN(timestamp)) return ''
    const now = Date.now() / 1000
    const diff = now - timestamp
    if (diff < 60) return '刚刚'
    if (diff < 3600) return Math.floor(diff / 60) + '分钟前'
    if (diff < 86400) return Math.floor(diff / 3600) + '小时前'
    if (diff < 2592000) return Math.floor(diff / 86400) + '天前'
    const d = new Date(timestamp * 1000)
    return `${d.getMonth() + 1}-${d.getDate()}`
}

const formatCount = (count: any) => {
    if (!count) return '0'
    const n = Number(count)
    if (n >= 10000) return (n / 10000).toFixed(1) + 'w'
    if (n >= 1000) return (n / 1000).toFixed(1) + 'k'
    return String(n)
}
</script>

<style lang="scss" scoped>
.post-card {
    display: flex;
    gap: 20rpx;
    padding: 28rpx;
    background: #fff;
    border-radius: 16rpx;
    margin: 0 24rpx 16rpx;

    &__avatar {
        width: 84rpx;
        height: 84rpx;
        border-radius: 12rpx;
        flex-shrink: 0;
    }

    &__body {
        flex: 1;
        min-width: 0;
        display: flex;
        flex-direction: column;
        gap: 10rpx;
    }

    &__main {
        display: flex;
        flex-direction: column;
        gap: 16rpx;
    }

    &__header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    &__user {
        display: flex;
        align-items: center;
        gap: 0;
        min-width: 0;
    }

    &__nickname {
        font-size: 28rpx;
        font-weight: 600;
        color: #000;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    &__dot {
        font-size: 24rpx;
        color: #666;
        margin: 0 8rpx;
        flex-shrink: 0;
    }

    &__time {
        font-size: 24rpx;
        color: #666;
        white-space: nowrap;
        flex-shrink: 0;
    }

    &__badges {
        display: flex;
        align-items: center;
        gap: 8rpx;
        flex-shrink: 0;
        margin-left: 12rpx;
    }

    &__badge {
        padding: 2rpx 10rpx;
        border-radius: 6rpx;
        font-size: 22rpx;
        line-height: 1.2;

        &--paid {
            background: #e5edff;

            text {
                color: #185dff;
            }
        }

        &--hot {
            background: #ffe5e5;

            text {
                color: #ee3835;
            }
        }

        &--top {
            background: #e5edff;

            text {
                color: #185dff;
            }
        }
    }

    &__content {
        line-height: 1.7;
    }

    &__text {
        font-size: 26rpx;
        color: #000;
        word-break: break-word;
        display: -webkit-box;
        -webkit-line-clamp: 5;
        -webkit-box-orient: vertical;
        overflow: hidden;

        &--locked {
            -webkit-line-clamp: 2;
        }
    }

    &__unlock {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 120rpx;
        padding: 0 24rpx;
        background: #e5edff;
        border-radius: 12rpx;
    }

    &__unlock-text {
        font-size: 28rpx;
        color: #185dff;
    }

    &__unlock-btn {
        height: 56rpx;
        padding: 0 24rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #185dff;
        border-radius: 12rpx;

        text {
            font-size: 28rpx;
            color: #fff;
        }
    }

    &__images {
        display: flex;
        gap: 12rpx;
        position: relative;

        &--full {
            display: block;
        }
    }

    &__img {
        flex: 1;
        height: 210rpx;
        border-radius: 12rpx;
        min-width: 0;

        &--full {
            display: block;
            width: 100%;
            height: auto;
            margin-bottom: 12rpx;
        }
    }

    &__img-more {
        position: absolute;
        right: 0;
        top: 0;
        width: 33.33%;
        height: 210rpx;
        border-radius: 12rpx;
        background: rgba(0, 0, 0, 0.4);
        display: flex;
        align-items: center;
        justify-content: center;

        text {
            font-size: 32rpx;
            color: #fff;
            font-weight: 600;
        }
    }

    &__external-cover {
        width: 100%;
        min-height: 210rpx;
        border-radius: 12rpx;
        padding: 24rpx;
        background: linear-gradient(135deg, #111827 0%, #1f2937 100%);
        display: flex;
        align-items: center;
        gap: 20rpx;
        box-sizing: border-box;
    }

    &__external-cover-icon {
        width: 76rpx;
        height: 76rpx;
        border-radius: 20rpx;
        background: rgba(255, 255, 255, 0.12);
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;

        text {
            font-size: 40rpx;
            color: #fff;
            font-weight: 700;
        }
    }

    &__external-cover-body {
        flex: 1;
        min-width: 0;
        display: flex;
        flex-direction: column;
        gap: 8rpx;
    }

    &__external-cover-title {
        font-size: 28rpx;
        color: #fff;
        font-weight: 600;
    }

    &__external-cover-desc {
        font-size: 24rpx;
        color: rgba(255, 255, 255, 0.72);
    }

    &__external-cover-btn {
        height: 60rpx;
        padding: 0 20rpx;
        border-radius: 999rpx;
        background: #185dff;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;

        text {
            font-size: 24rpx;
            color: #fff;
            font-weight: 600;
        }
    }

    &__translate {
        margin-top: 10rpx;
        padding-left: 4rpx;

        &-text {
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
            overflow: hidden;
            font-size: 28rpx;
            color: #3f4a5a;
            line-height: 1.75;
            word-break: break-word;
            white-space: pre-wrap;
        }
    }

    &__tags {
        display: flex;
        flex-wrap: wrap;
        gap: 10rpx;
    }

    &__tag {
        padding: 2rpx 10rpx;
        border-radius: 6rpx;
        background: #e5edff;

        text {
            font-size: 22rpx;
            color: #185dff;
        }
    }

    &__actions {
        display: flex;
        align-items: center;
        gap: 40rpx;
    }

    &__action {
        display: flex;
        align-items: center;
        gap: 6rpx;

        &--active {

            .post-card__action-icon,
            .post-card__action-num {
                color: #185dff;
            }
        }
    }

    &__action-icon {
        font-size: 28rpx;
        color: #262626;
        line-height: 1;
    }

    &__action-num {
        font-size: 24rpx;
        color: #262626;
    }
}
</style>
