<template>
    <view class="post-card" @tap="$emit('tap')">
        <view v-if="post.is_paid && !post.is_unlocked" class="post-card__topbar">
            <view class="post-card__paid-notice">
                <u-icon name="lock" size="25" color="#1468f5" />
                <text>付费内容 · {{ post.price_points }} 积分</text>
            </view>
            <view class="post-card__status">
                <text class="post-card__price">{{ post.price_points }} 积分</text>
                <u-icon name="more-dot-fill" size="30" color="#8d96a3" />
            </view>
        </view>

        <view class="post-card__header"
            :class="{ 'post-card__header--corner-status': !post.is_paid || post.is_unlocked }">
            <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__author">
                <view class="post-card__identity">
                    <text class="post-card__nickname">{{ post.user?.nickname || '匿名用户' }}</text>
                    <text v-if="post.user?.id && post.user.fans_count > 0" class="post-card__follow-count">关注 {{
                        formatCount(post.user.fans_count)
                        }}</text>
                    <text v-if="post.is_top" class="post-card__pin">置顶</text>
                </view>
                <text class="post-card__time">{{ formatTime(post.create_time) }}</text>
            </view>
            <view v-if="!post.is_paid || post.is_unlocked" class="post-card__status post-card__status--corner">
                <text class="post-card__free">免费</text>
                <u-icon name="more-dot-fill" size="30" color="#8d96a3" />
            </view>
        </view>

        <view class="post-card__content">
            <text v-if="contentTitle" class="post-card__title">{{ contentTitle }}</text>
            <text class="post-card__summary"
                :class="{ 'post-card__summary--locked': post.is_paid && !post.is_unlocked }">
                {{ contentSummary }}
            </text>
        </view>

        <view v-if="displayTranslatedText" class="post-card__translation">
            <text>AI 翻译</text>
            <text class="post-card__translation-text">{{ displayTranslatedText }}</text>
        </view>

        <view v-if="post.is_paid && !post.is_unlocked" class="post-card__unlock" @tap.stop="$emit('unlock')">
            <view>
                <text class="post-card__unlock-title">深度内容待解锁</text>
                <text class="post-card__unlock-desc">解锁后阅读完整分析与讨论</text>
            </view>
            <view class="post-card__unlock-btn">查看详情</view>
        </view>

        <view v-if="post.images?.length && !(post.is_paid && !post.is_unlocked)" class="post-card__images"
            :class="{ 'post-card__images--full': isLotteryPost }">
            <template v-if="isLotteryPost">
                <image v-for="(image, index) in post.images" :key="index"
                    class="post-card__image post-card__image--full" :src="image" mode="widthFix"
                    @tap.stop="previewImage(index)" />
            </template>
            <template v-else-if="trumpSourceUrl">
                <view class="post-card__external-cover" @tap.stop="openSourceUrl">
                    <view class="post-card__external-cover-icon">T</view>
                    <view class="post-card__external-cover-copy">
                        <text>Truth Social 图片暂不可直连</text>
                        <text>点击查看原帖</text>
                    </view>
                    <u-icon name="arrow-right" size="26" color="#ffffff" />
                </view>
            </template>
            <template v-else>
                <image v-for="(image, index) in post.images.slice(0, 3)" :key="index" class="post-card__image"
                    :src="image" mode="aspectFill" @tap.stop="previewImage(index)" />
                <view v-if="post.images.length > 3" class="post-card__image-more" @tap.stop="previewImage(3)">
                    <text>+{{ post.images.length - 3 }}</text>
                </view>
            </template>
        </view>

        <view v-if="post.tags?.length" class="post-card__tags">
            <view v-for="(tag, index) in post.tags" :key="index" class="post-card__tag">{{ tag }}</view>
        </view>

        <view class="post-card__actions">
            <view class="post-card__action" @tap.stop="$emit('tap')">
                <u-icon name="eye" size="31" color="#7a8494" />
                <text>{{ formatCount(post.view_count) }}</text>
            </view>
            <view class="post-card__action" @tap.stop="$emit('tap')">
                <u-icon name="chat" size="30" color="#7a8494" />
                <text>{{ formatCount(post.comment_count) }}</text>
            </view>
            <view class="post-card__action" :class="{ 'post-card__action--active': post.is_liked }"
                @tap.stop="$emit('like')">
                <u-icon :name="post.is_liked ? 'thumb-up-fill' : 'thumb-up'" size="31"
                    :color="post.is_liked ? '#1468f5' : '#7a8494'" />
                <text>{{ formatCount(post.like_count) }}</text>
            </view>
        </view>
    </view>
</template>

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

const props = defineProps<{ post: any }>()
defineEmits(['tap', 'unlock', 'like', 'avatar-tap'])
const translatedText = ref('')
const cachedContent = ref(props.post.translated_content || '')
const autoTranslateStarted = ref(false)

const rawContent = computed(() => String(props.post?.content_short || props.post?.content || '').trim())
const contentParts = computed(() => {
    const lines = rawContent.value.split('\n').map((line) => line.trim()).filter(Boolean)
    const firstLine = lines[0] || ''
    if (lines.length > 1 && firstLine.length <= 58) {
        return { title: firstLine, summary: lines.slice(1).join('\n') }
    }
    return { title: '', summary: rawContent.value }
})
const contentTitle = computed(() => contentParts.value.title)
const contentSummary = computed(() => contentParts.value.summary)
const isLotteryPost = computed(() => Array.isArray(props.post?.tags) && props.post.tags.includes('彩票'))
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]
    return postId ? `https://truthsocial.com/@realDonaldTrump/${postId}` : ''
})
const displayTranslatedText = computed(() => translatedText.value || cachedContent.value || props.post?.translated_content || '')

const openSourceUrl = () => trumpSourceUrl.value && uni.navigateTo({ url: `/pages/webview/webview?url=${encodeURIComponent(trumpSourceUrl.value)}` })
const previewImage = (index: number) => {
    const images = props.post?.images || []
    if (images.length) uni.previewImage({ urls: images, current: images[index] || images[0] })
}

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

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 = (value: any) => {
    if (!value) return ''
    const timestamp = typeof value === 'string' ? new Date(value.replace(/-/g, '/')).getTime() / 1000 : Number(value)
    if (Number.isNaN(timestamp)) return ''
    const seconds = Date.now() / 1000 - timestamp
    if (seconds < 60) return '刚刚发布'
    if (seconds < 3600) return `${Math.floor(seconds / 60)} 分钟前`
    if (seconds < 86400) return `${Math.floor(seconds / 3600)} 小时前`
    if (seconds < 2592000) return `${Math.floor(seconds / 86400)} 天前`
    const date = new Date(timestamp * 1000)
    return `${date.getMonth() + 1}-${date.getDate()}`
}

const formatCount = (value: any) => {
    const numericValue = Number(value)
    if (!Number.isFinite(numericValue) || numericValue <= 0) return '0'

    const count = Math.floor(numericValue)
    const compact = (divisor: number, unit: string) => {
        const formatted = (count / divisor).toFixed(1).replace(/\.0$/, '')
        return `${formatted}${unit}`
    }

    if (count >= 100000000) return compact(100000000, '亿')
    if (count >= 10000) return compact(10000, '万')
    if (count >= 1000) return compact(1000, 'k')
    return String(count)
}
</script>

<style lang="scss" scoped>
.post-card {
    position: relative;
    margin: 0 26rpx 18rpx;
    padding: 26rpx 26rpx 22rpx;
    border: 1rpx solid rgba(225, 231, 240, 0.86);
    border-radius: 24rpx;
    background: #fff;
    box-shadow: 0 8rpx 24rpx rgba(31, 54, 89, 0.055);
    box-sizing: border-box;

    &__topbar {
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        gap: 20rpx;
        margin: -2rpx 0 20rpx;
        min-width: 0;

        .post-card__status {
            align-self: flex-start;
            margin-left: auto;
        }
    }

    &__paid-notice {
        display: flex;
        align-items: center;
        gap: 8rpx;
        min-width: 0;
        color: #1468f5;
        font-size: 24rpx;
        font-weight: 600;
        white-space: nowrap;
    }

    &__header {
        display: flex;
        align-items: center;
        min-width: 0;

        &--corner-status {
            padding-right: 132rpx;
            box-sizing: border-box;
        }
    }

    &__avatar {
        width: 78rpx;
        height: 78rpx;
        margin-right: 16rpx;
        border-radius: 50%;
        flex-shrink: 0;
        background: #eef2f8;
    }

    &__author {
        flex: 1;
        min-width: 0;
    }

    &__identity,
    &__status {
        display: flex;
        align-items: center;
    }

    &__identity {
        min-width: 0;
        gap: 9rpx;
    }

    &__nickname {
        max-width: 220rpx;
        overflow: hidden;
        color: #202a3b;
        font-size: 29rpx;
        font-weight: 700;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    &__follow-count {
        min-width: 0;
        padding: 5rpx 14rpx;
        border-radius: 999rpx;
        color: #fff;
        font-size: 20rpx;
        font-weight: 600;
        line-height: 1.1;
        white-space: nowrap;
        background: linear-gradient(135deg, #2480ff 0%, #0d63ed 100%);
        box-shadow: 0 4rpx 10rpx rgba(20, 104, 245, 0.2);
        flex-shrink: 0;
    }

    &__pin,
    &__free,
    &__price {
        padding: 4rpx 12rpx;
        border-radius: 8rpx;
        color: #4f4f4f;
        font-size: 20rpx;
        font-weight: 500;
        background: #e9e9e9;
    }

    &__time {
        display: block;
        margin-top: 5rpx;
        color: #9099a8;
        font-size: 23rpx;
    }

    &__status {
        gap: 15rpx;
        margin-left: 14rpx;
        flex-shrink: 0;

        &--corner {
            position: absolute;
            top: 26rpx;
            right: 26rpx;
            margin-left: 0;
        }
    }

    &__price {
        color: #7653d6;
        background: #f1edff;
    }

    &__content {
        display: flex;
        flex-direction: column;
        gap: 10rpx;
        padding: 24rpx 0 0;
    }

    &__title {
        color: #172033;
        font-size: 34rpx;
        font-weight: 700;
        line-height: 1.38;
    }

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

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

    &__translation {
        display: flex;
        flex-direction: column;
        gap: 8rpx;
        margin-top: 16rpx;
        padding: 16rpx 18rpx;
        border-left: 4rpx solid #94bbff;
        border-radius: 0 12rpx 12rpx 0;
        background: #f5f8ff;

        >text:first-child {
            color: #1468f5;
            font-size: 21rpx;
            font-weight: 700;
        }
    }

    &__translation-text {
        display: -webkit-box;
        overflow: hidden;
        color: #59667a;
        font-size: 25rpx;
        line-height: 1.55;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 3;
    }

    &__unlock {
        min-height: 180rpx;
        display: flex;
        flex-direction: column;
        align-items: stretch;
        justify-content: space-between;
        gap: 20rpx;
        margin-top: 20rpx;
        padding: 24rpx 26rpx 18rpx;
        overflow: hidden;
        border-radius: 16rpx;
        background: linear-gradient(180deg,
                rgba(205, 218, 232, 0.96) 0%,
                rgba(228, 236, 244, 0.86) 52%,
                rgba(255, 255, 255, 0.98) 100%);
        box-sizing: border-box;
    }

    &__unlock-title {
        display: block;
        color: #31445f;
        font-size: 27rpx;
        font-weight: 700;
    }

    &__unlock-desc {
        display: block;
        margin-top: 6rpx;
        color: #718098;
        font-size: 22rpx;
    }

    &__unlock-btn {
        width: 320rpx;
        height: 64rpx;
        align-self: center;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 2rpx solid #1468f5;
        border-radius: 999rpx;
        background: rgba(255, 255, 255, 0.72);
        color: #1468f5;
        font-size: 24rpx;
        font-weight: 600;
        box-sizing: border-box;
        flex-shrink: 0;
    }

    &__images {
        position: relative;
        display: flex;
        gap: 10rpx;
        margin-top: 20rpx;
        overflow: hidden;
        border-radius: 16rpx;

        &--full {
            display: block;
        }
    }

    &__image {
        width: calc((100% - 20rpx) / 3);
        height: 184rpx;
        border-radius: 14rpx;
        background: #eef2f8;

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

    &__image-more {
        position: absolute;
        right: 0;
        top: 0;
        width: calc((100% - 20rpx) / 3);
        height: 184rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 14rpx;
        color: #fff;
        font-size: 31rpx;
        font-weight: 700;
        background: rgba(18, 29, 48, 0.58);
    }

    &__external-cover {
        width: 100%;
        min-height: 176rpx;
        display: flex;
        align-items: center;
        gap: 18rpx;
        padding: 22rpx;
        color: #fff;
        background: linear-gradient(135deg, #172033, #34425a);
        box-sizing: border-box;
    }

    &__external-cover-icon {
        width: 64rpx;
        height: 64rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 18rpx;
        font-size: 33rpx;
        font-weight: 700;
        background: rgba(255, 255, 255, 0.16);
    }

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

        text:first-child {
            font-size: 26rpx;
            font-weight: 600;
        }

        text:last-child {
            color: rgba(255, 255, 255, 0.7);
            font-size: 22rpx;
        }
    }

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

    &__tag {
        padding: 5rpx 13rpx;
        border-radius: 8rpx;
        color: #1468f5;
        font-size: 22rpx;
        background: #edf4ff;
    }

    &__actions {
        display: flex;
        align-items: center;
        margin-top: 22rpx;
        padding-top: 18rpx;
        border-top: 1rpx solid #edf0f4;
    }

    &__action {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 7rpx;
        color: #7a8494;
        font-size: 24rpx;
        line-height: 1;

        &--active {
            color: #1468f5;
        }
    }
}
</style>
