<template>
    <view class="match-detail">
        <match-detail-header :status-bar-height="statusBarHeight" title="赛事详情"
            :subtitle="match.league_name || '赛事信息加载中'" @back="goBack" @share="showSharePopup = true" />

        <!-- 加载中 -->
        <view class="detail-loading" v-if="loading">
            <u-loading mode="circle"></u-loading>
            <text>加载中...</text>
        </view>

        <!-- 内容区域 -->
        <scroll-view v-else scroll-y class="detail-content" :style="{ height: contentHeight + 'px' }">
            <!-- 比赛信息卡片：进行中/已结束 -->
            <view class="match-info-wrap" v-if="match.status !== 0">
                <match-card :match="match" />
            </view>

            <!-- 比赛信息卡片：未开始 -->
            <view class="match-info-wrap" v-else>
                <view class="upcoming-card">
                    <view class="upcoming-card__header">
                        <view class="upcoming-card__tags">
                            <text class="upcoming-card__league">{{ match.league_name }}</text>
                            <view v-if="match.round_name" class="upcoming-card__tag upcoming-card__tag--blue">
                                <text>{{ match.round_name }}</text>
                            </view>
                            <view v-if="match.is_hot" class="upcoming-card__hot">
                                <text>热</text>
                            </view>
                        </view>
                    </view>
                    <view class="upcoming-card__teams">
                        <view class="upcoming-card__team">
                            <image v-if="match.home_icon" class="upcoming-card__icon" :src="match.home_icon"
                                mode="aspectFit" />
                            <text class="upcoming-card__name">{{ match.home_team }}</text>
                        </view>
                        <view class="upcoming-card__center">
                            <text class="upcoming-card__score">0</text>
                            <text class="upcoming-card__vs">VS</text>
                            <text class="upcoming-card__score">0</text>
                        </view>
                        <view class="upcoming-card__team">
                            <image v-if="match.away_icon" class="upcoming-card__icon" :src="match.away_icon"
                                mode="aspectFit" />
                            <text class="upcoming-card__name">{{ match.away_team }}</text>
                        </view>
                    </view>
                    <view class="upcoming-card__divider"></view>
                    <view class="upcoming-card__footer">
                        <view class="upcoming-card__status">
                            <text>未开始</text>
                        </view>
                        <text class="upcoming-card__time">{{ formatMatchTime(match.match_time) }}</text>
                    </view>
                </view>
            </view>

            <view v-if="liveList.length" class="live-entrance">
                <view class="live-entrance__player-card">
                    <view class="live-entrance__player-header">
                        <view class="live-entrance__player-title-wrap">
                            <text class="live-entrance__player-title">{{ activeLiveLineTitle }}</text>
                        </view>
                        <view class="live-entrance__player-actions">
                            <u-button v-if="activeLivePlayUrl" size="mini" shape="circle" plain
                                @click.stop="openLiveFullscreen">
                                全屏播放
                            </u-button>
                            <u-button size="mini" shape="circle" plain @click.stop="toggleLiveLineSelector">
                                {{ showLiveLineSelector ? '收起线路' : '切换线路' }}
                            </u-button>
                        </view>
                    </view>

                    <view v-if="activeLivePlayUrl" class="live-entrance__player-wrap">
                        <video id="match-live-player" :key="activeLivePlayerKey" class="live-entrance__player"
                            :src="activeLivePlayUrl" :poster="match.home_icon || match.away_icon || ''" :autoplay="true"
                            :controls="true" :show-play-btn="true" :show-center-play-btn="true" :show-progress="false"
                            :show-fullscreen-btn="true" :page-gesture="true" object-fit="contain"
                            @play="handleLivePlayerPlay" @loadedmetadata="handleLivePlayerLoaded"
                            @waiting="handleLivePlayerWaiting" @error="handleLivePlayerError" />
                    </view>
                    <view v-else class="live-entrance__player-empty">
                        <text class="live-entrance__player-empty-title">当前线路暂无可用直播放流</text>
                        <text class="live-entrance__player-empty-desc">可切换其他线路，或打开当前线路源站继续观看</text>
                        <u-button v-if="activeLiveSourceUrl" size="mini" shape="circle" plain
                            class="live-entrance__empty-action" @click.stop="openActiveLiveSource">
                            打开当前线路源站
                        </u-button>
                    </view>

                    <text v-if="activeLiveError" class="live-entrance__player-error">{{ activeLiveError }}</text>

                    <view v-if="showLiveLineSelector" class="live-entrance__selector">
                        <view v-for="(item, index) in resolvedLiveList" :key="item.lineKey"
                            class="live-entrance__selector-item"
                            :class="{ 'live-entrance__selector-item--active': item.lineKey === activeLiveLineKey }"
                            @tap="selectLiveLine(item)">
                            <view class="live-entrance__selector-main">
                                <view class="live-entrance__selector-index">
                                    <text>{{ index + 1 }}</text>
                                </view>
                                <view class="live-entrance__selector-content">
                                    <text class="live-entrance__selector-title">{{ item.displayTitle }}</text>
                                    <text class="live-entrance__selector-desc">{{ item.metaText }}</text>
                                </view>
                            </view>
                            <text class="live-entrance__selector-tag">
                                {{ item.lineKey === activeLiveLineKey ? '当前播放' : item.hasDirectPlay ? '点击切换' : '源站兜底' }}
                            </text>
                        </view>
                    </view>
                </view>
            </view>

            <!-- Tab 导航栏 -->
            <view v-else-if="thirdPartyLiveUrl" class="live-entrance">
                <view class="live-entrance__fallback-card" @tap="openThirdPartyLive">
                    <view class="live-entrance__left">
                        <view class="live-entrance__badge">
                            <text>直播</text>
                        </view>
                        <view class="live-entrance__content">
                            <text class="live-entrance__title">直播详情</text>
                            <text class="live-entrance__desc">
                                {{ liveSourceText || '点击进入第三方直播页查看实时内容' }}
                            </text>
                        </view>
                    </view>
                    <view class="live-entrance__action">
                        <text>立即查看</text>
                        <u-icon name="arrow-right" size="26" color="#c7d2fe"></u-icon>
                    </view>
                </view>
            </view>

            <scroll-view scroll-x class="detail-tabs" show-scrollbar="false">
                <view class="detail-tabs__inner">
                    <view v-for="tab in tabList" :key="tab.key" class="detail-tabs__item"
                        :class="{ 'detail-tabs__item--active': activeTab === tab.key }" @tap="activeTab = tab.key">
                        <text>{{ tab.label }}</text>
                        <view v-if="tab.key === 'live' && match.status === 1" class="detail-tabs__dot"></view>
                    </view>
                </view>
            </scroll-view>

            <!-- Tab 内容区：固定高度可滚动 -->
            <view class="detail-tab-body">
                <!-- ====== 文字直播 ====== -->
                <scroll-view v-if="activeTab === 'live'" scroll-y class="detail-tab-scroll">
                    <view v-if="liveTextList.length" class="live-text">
                        <view class="live-text__item" v-for="item in [...liveTextList].reverse()" :key="item.msg_id">
                            <view class="live-text__left">
                                <image v-if="item.avatar" class="live-text__avatar" :src="item.avatar"
                                    mode="aspectFill" />
                                <view v-else class="live-text__avatar live-text__avatar--default">
                                    <text>{{ (item.username || '').slice(0, 1) }}</text>
                                </view>
                            </view>
                            <view class="live-text__right">
                                <view class="live-text__meta">
                                    <text class="live-text__name">{{ item.username }}</text>
                                    <text class="live-text__time">{{ formatLiveTime(item.create_time || item.timestamp)
                                    }}</text>
                                </view>
                                <text class="live-text__msg">{{ item.message }}</text>
                                <image v-if="item.image" class="live-text__image" :src="item.image" mode="widthFix"
                                    @tap="previewLiveImage(item.image)" />
                            </view>
                        </view>
                    </view>
                    <view v-else class="live-text__empty">
                        <text>暂无文字直播数据</text>
                    </view>
                </scroll-view>

                <!-- ====== 比赛数据 ====== -->
                <scroll-view v-if="activeTab === 'data'" scroll-y class="detail-tab-scroll">
                    <!-- 赔率 -->
                    <view class="tab-card" v-if="showLegacyMatchOdds && match.home_odds > 0">
                        <view class="tab-card__title"><text>赔率信息</text></view>
                        <view class="match-odds">
                            <view class="match-odds__item">
                                <text class="match-odds__label">主胜</text>
                                <text class="match-odds__value">{{ match.home_odds }}</text>
                            </view>
                            <view class="match-odds__item">
                                <text class="match-odds__label">平</text>
                                <text class="match-odds__value">{{ match.draw_odds || '0.00' }}</text>
                            </view>
                            <view class="match-odds__item">
                                <text class="match-odds__label">客胜</text>
                                <text class="match-odds__value">{{ match.away_odds }}</text>
                            </view>
                        </view>
                    </view>
                    <!-- 技术统计 -->
                    <view class="tab-card" v-if="match.status !== 0">
                        <view class="tab-card__title"><text>技术统计</text></view>
                        <view class="tech-stats">
                            <view class="tech-stats__row" v-for="s in techStatsList" :key="s.label">
                                <view class="tech-stats__nums">
                                    <text class="tech-stats__home-val">{{ s.home }}</text>
                                    <text class="tech-stats__label">{{ s.label }}</text>
                                    <text class="tech-stats__away-val">{{ s.away }}</text>
                                </view>
                                <view class="tech-stats__bars">
                                    <view class="tech-stats__bar tech-stats__bar--home"
                                        :style="{ width: s.homePct + '%' }"></view>
                                    <view class="tech-stats__bar tech-stats__bar--away"
                                        :style="{ width: s.awayPct + '%' }"></view>
                                </view>
                            </view>
                        </view>
                    </view>
                    <!-- 精彩瞬间 暂时隐藏 -->
                    <!-- <view class="tab-card" v-if="match.events && match.events.length">
                        <view class="tab-card__title"><text>精彩瞬间</text></view>
                        <view class="match-events">
                            <view class="match-events__item" v-for="evt in match.events" :key="evt.id">
                                <view class="match-events__time">
                                    <text class="match-events__minute">{{ evt.minute }}'</text>
                                    <view class="match-events__dot"
                                        :class="'match-events__dot--' + eventColor(evt.event_type)"></view>
                                </view>
                                <view class="match-events__info">
                                    <view class="match-events__header">
                                        <text class="match-events__type">{{ eventTypeText(evt.event_type) }}</text>
                                        <text class="match-events__side"
                                            :class="evt.team_side === 1 ? 'match-events__side--home' : 'match-events__side--away'">
                                            {{ evt.team_side === 1 ? match.home_team : match.away_team }}</text>
                                    </view>
                                    <text class="match-events__player">{{ evt.player_name }}</text>
                                </view>
                            </view>
                        </view>
                    </view> -->
                    <view v-if="match.status === 0" class="live-text__empty">
                        <text>比赛尚未开始</text>
                    </view>
                </scroll-view>

                <!-- ====== 赔率 ====== -->
                <scroll-view v-if="activeTab === 'odds'" scroll-y class="detail-tab-scroll">
                    <MatchOddsDetail :home-team="match.home_team" :away-team="match.away_team"
                        :match-time="match.match_time" :competition-id="match.competition_id"
                        :league-name="match.league_name" />
                </scroll-view>

                <!-- ====== 阵容 ====== -->
                <scroll-view v-if="activeTab === 'lineup'" scroll-y class="detail-tab-scroll">
                    <view v-if="lineupList.length">
                        <!-- 主队首发 -->
                        <view class="tab-card">
                            <view class="tab-card__title">
                                <image v-if="match.home_icon" class="tab-card__team-icon" :src="match.home_icon"
                                    mode="aspectFit" />
                                <text>{{ match.home_team }} 首发</text>
                            </view>
                            <view class="lineup-grid">
                                <view class="lineup-player" v-for="p in homeStarters" :key="p.id">
                                    <image v-if="p.person_logo" class="lineup-player__avatar" :src="p.person_logo"
                                        mode="aspectFill" />
                                    <view v-else class="lineup-player__avatar lineup-player__avatar--default">
                                        <text>{{ p.shirt_number || '#' }}</text>
                                    </view>
                                    <text class="lineup-player__name">{{ p.person_name }}</text>
                                    <text class="lineup-player__pos">{{ p.position || '' }}</text>
                                </view>
                            </view>
                        </view>
                        <!-- 主队替补 -->
                        <view class="tab-card" v-if="homeSubs.length">
                            <view class="tab-card__title"><text>{{ match.home_team }} 替补</text></view>
                            <view class="lineup-grid">
                                <view class="lineup-player" v-for="p in homeSubs" :key="p.id">
                                    <image v-if="p.person_logo" class="lineup-player__avatar" :src="p.person_logo"
                                        mode="aspectFill" />
                                    <view v-else class="lineup-player__avatar lineup-player__avatar--default">
                                        <text>{{ p.shirt_number || '#' }}</text>
                                    </view>
                                    <text class="lineup-player__name">{{ p.person_name }}</text>
                                    <text class="lineup-player__pos">{{ p.position || '' }}</text>
                                </view>
                            </view>
                        </view>
                        <!-- 客队首发 -->
                        <view class="tab-card">
                            <view class="tab-card__title">
                                <image v-if="match.away_icon" class="tab-card__team-icon" :src="match.away_icon"
                                    mode="aspectFit" />
                                <text>{{ match.away_team }} 首发</text>
                            </view>
                            <view class="lineup-grid">
                                <view class="lineup-player" v-for="p in awayStarters" :key="p.id">
                                    <image v-if="p.person_logo" class="lineup-player__avatar" :src="p.person_logo"
                                        mode="aspectFill" />
                                    <view v-else class="lineup-player__avatar lineup-player__avatar--default">
                                        <text>{{ p.shirt_number || '#' }}</text>
                                    </view>
                                    <text class="lineup-player__name">{{ p.person_name }}</text>
                                    <text class="lineup-player__pos">{{ p.position || '' }}</text>
                                </view>
                            </view>
                        </view>
                        <!-- 客队替补 -->
                        <view class="tab-card" v-if="awaySubs.length">
                            <view class="tab-card__title"><text>{{ match.away_team }} 替补</text></view>
                            <view class="lineup-grid">
                                <view class="lineup-player" v-for="p in awaySubs" :key="p.id">
                                    <image v-if="p.person_logo" class="lineup-player__avatar" :src="p.person_logo"
                                        mode="aspectFill" />
                                    <view v-else class="lineup-player__avatar lineup-player__avatar--default">
                                        <text>{{ p.shirt_number || '#' }}</text>
                                    </view>
                                    <text class="lineup-player__name">{{ p.person_name }}</text>
                                    <text class="lineup-player__pos">{{ p.position || '' }}</text>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view v-else class="live-text__empty">
                        <text>暂无阵容数据</text>
                    </view>
                </scroll-view>

                <!-- ====== 近期战绩 ====== -->
                <scroll-view v-if="activeTab === 'recent'" scroll-y class="detail-tab-scroll">
                    <!-- 对赛往绩 -->
                    <view class="tab-card" v-if="match.history && match.history.length">
                        <view class="tab-card__title"><text>对赛往绩</text></view>
                        <view class="match-history">
                            <view class="match-history__item" v-for="h in match.history" :key="h.id">
                                <view class="match-history__date"><text>{{ formatTs(h.match_time) }}</text></view>
                                <view class="match-history__teams">
                                    <text class="match-history__team">{{ h.home_team }}</text>
                                    <text class="match-history__score">{{ h.home_score }} - {{ h.away_score }}</text>
                                    <text class="match-history__team">{{ h.away_team }}</text>
                                </view>
                                <text class="match-history__league">{{ h.league_name }}</text>
                            </view>
                        </view>
                    </view>
                    <!-- 主队近期 -->
                    <view class="tab-card" v-if="match.home_recent && match.home_recent.length">
                        <view class="tab-card__title">
                            <image v-if="match.home_icon" class="tab-card__team-icon" :src="match.home_icon"
                                mode="aspectFit" />
                            <text>{{ match.home_team }} 近期</text>
                        </view>
                        <view class="match-recent">
                            <view class="match-recent__item" v-for="r in match.home_recent" :key="r.id">
                                <view class="match-recent__left">
                                    <text class="match-recent__result" :class="'match-recent__result--' + r.result">{{
                                        resultText(r.result) }}</text>
                                    <text class="match-recent__vs">VS</text>
                                    <text class="match-recent__opponent">{{ r.opponent }}</text>
                                </view>
                                <view class="match-recent__right">
                                    <view class="match-recent__score">
                                        <text class="match-recent__score-num">{{ r.team_score }}</text>
                                        <text class="match-recent__score-sep">-</text>
                                        <text class="match-recent__score-num">{{ r.opponent_score }}</text>
                                    </view>
                                    <text class="match-recent__date">{{ formatTs(r.match_time) }}</text>
                                </view>
                            </view>
                        </view>
                    </view>
                    <!-- 客队近期 -->
                    <view class="tab-card" v-if="match.away_recent && match.away_recent.length">
                        <view class="tab-card__title">
                            <image v-if="match.away_icon" class="tab-card__team-icon" :src="match.away_icon"
                                mode="aspectFit" />
                            <text>{{ match.away_team }} 近期</text>
                        </view>
                        <view class="match-recent">
                            <view class="match-recent__item" v-for="r in match.away_recent" :key="r.id">
                                <view class="match-recent__left">
                                    <text class="match-recent__result" :class="'match-recent__result--' + r.result">{{
                                        resultText(r.result) }}</text>
                                    <text class="match-recent__vs">VS</text>
                                    <text class="match-recent__opponent">{{ r.opponent }}</text>
                                </view>
                                <view class="match-recent__right">
                                    <view class="match-recent__score">
                                        <text class="match-recent__score-num">{{ r.team_score }}</text>
                                        <text class="match-recent__score-sep">-</text>
                                        <text class="match-recent__score-num">{{ r.opponent_score }}</text>
                                    </view>
                                    <text class="match-recent__date">{{ formatTs(r.match_time) }}</text>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view
                        v-if="!(match.history?.length) && !(match.home_recent?.length) && !(match.away_recent?.length)"
                        class="live-text__empty">
                        <text>暂无战绩数据</text>
                    </view>
                </scroll-view>

                <!-- ====== AI分析 ====== -->
                <scroll-view v-if="activeTab === 'ai'" scroll-y class="detail-tab-scroll">
                    <!-- 已解锁 -->
                    <view v-if="aiUnlocked" class="tab-card">
                        <view class="tab-card__title">
                            <text>AI智能分析</text>
                            <text class="tab-card__badge tab-card__badge--green">已解锁</text>
                        </view>
                        <view v-if="aiInline.prediction" class="match-ai-inline">
                            <view class="match-ai-inline__row">
                                <text class="match-ai-inline__label">预测结果</text>
                                <text class="match-ai-inline__val match-ai-inline__val--highlight">{{
                                    aiInline.prediction?.prediction?.result || '待分析' }}</text>
                            </view>
                            <view class="match-ai-inline__row">
                                <text class="match-ai-inline__label">置信度</text>
                                <text class="match-ai-inline__val">{{ aiInline.prediction?.prediction?.confidence || 0
                                }}%</text>
                            </view>
                            <view class="match-ai-inline__row">
                                <text class="match-ai-inline__label">比分预测</text>
                                <text class="match-ai-inline__val">{{ aiInline.prediction?.prediction?.score_predict ||
                                    '-' }}</text>
                            </view>
                            <view v-if="aiInline.prediction?.prediction?.reasoning" class="match-ai-inline__reasoning">
                                <text>{{ aiInline.prediction.prediction.reasoning }}</text>
                            </view>
                        </view>
                        <view v-if="aiInline.factors?.key_factors?.length" class="match-ai-inline__tags">
                            <text class="match-ai-inline__label">关键因素</text>
                            <view class="match-ai-inline__tag-wrap">
                                <text v-for="(f, i) in aiInline.factors.key_factors" :key="i"
                                    class="match-ai-inline__tag match-ai-inline__tag--green">{{ f }}</text>
                            </view>
                        </view>
                        <view v-if="aiInline.odds?.odds_opinion" class="match-ai-inline__row">
                            <text class="match-ai-inline__label">赔率推荐</text>
                            <text class="match-ai-inline__val match-ai-inline__val--highlight">{{
                                aiInline.odds.odds_opinion.value_bet }}</text>
                        </view>
                        <view v-if="aiInline.summary?.summary" class="match-ai-inline__summary">
                            <text>{{ aiInline.summary.summary }}</text>
                        </view>
                        <view v-if="aiInlineLoading" class="match-ai-inline__loading">
                            <text>AI分析加载中...</text>
                        </view>
                        <view class="match-ai-inline__more" @tap="goAiAnalysis">
                            <text>查看完整分析 ›</text>
                        </view>
                    </view>
                    <!-- 未解锁 -->
                    <view v-else class="tab-card">
                        <view class="match-ai" @tap="goAiAnalysis">
                            <view class="match-ai__badge">AI</view>
                            <view class="match-ai__content">
                                <text class="match-ai__title">获取AI赛事深度分析</text>
                                <text class="match-ai__desc">基于大数据的智能预测与胜负分析</text>
                            </view>
                            <view class="match-ai__arrow"><text>›</text></view>
                        </view>
                        <view class="match-ai__vip-info">
                            <text v-if="isVipUser" class="match-ai__vip-tag match-ai__vip-tag--vip">VIP</text>
                            <text v-if="isVipUser" class="match-ai__vip-text">尊贵的{{ vipLevelName }}，到期时间{{ vipExpireDate
                            }}</text>
                            <text v-if="!isVipUser" class="match-ai__vip-tag">免费</text>
                            <text v-if="!isVipUser" class="match-ai__vip-text">{{ AI_DAILY_FREE_TEXT }}，今日剩余{{ freeRemain }}次</text>
                        </view>
                    </view>
                </scroll-view>
            </view>
        </scroll-view>

        <!-- 分享弹窗 -->
        <SharePopup v-if="showSharePopup" v-model:show="showSharePopup" page-type="match"
            :path="`/pages/match_detail/match_detail?id=${match.id || ''}`"
            :title="(match.home_team || '') + ' vs ' + (match.away_team || '')" />
        <GlobalPopup />
    </view>
</template>

<script lang="ts" setup>
import { ref, computed, nextTick, onMounted, watch } from 'vue'
import MatchDetailHeader from '@/components/match-detail-header/match-detail-header.vue'
import MatchOddsDetail from '@/components/match-odds-detail/match-odds-detail.vue'
import SharePopup from '@/components/share-popup/share-popup.vue'
import GlobalPopup from '@/components/global-popup/global-popup.vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { getMatchDetail, getMatchLiveText, getMatchLineup } from '@/api/match'
import type { MatchLiveLineItem } from '@/api/match'
import { checkAiUnlock, getMatchPredictSection } from '@/api/ai'
import { useUserStore } from '@/stores/user'
import { getLocalMatchDate } from '@/utils/match-time'
import { AI_DAILY_FREE_TEXT, getAiFreeRemain } from '@/config/ai'

type MatchDetailLiveLine = MatchLiveLineItem & {
    lineKey: string
    displayTitle: string
    metaText: string
    playUrl: string
    sourceUrl: string
    hasDirectPlay: boolean
}

const userStore = useUserStore()
const vipInfo = computed(() => userStore.userInfo?.vip_info || {})
const isVipUser = computed(() => !!vipInfo.value.is_vip)
const vipLevelName = computed(() => vipInfo.value.vip_level_name || '会员')
const vipExpireDate = computed(() => vipInfo.value.vip_expire_time || '')
const freeRemain = ref(getAiFreeRemain(vipInfo.value))

const statusBarHeight = ref(0)
const contentHeight = ref(500)
const loading = ref(true)
const match = ref<any>({})
const aiUnlocked = ref(false)
const aiInlineLoading = ref(false)
const aiInline = ref<any>({})
const showSharePopup = ref(false)
const liveTextList = ref<any[]>([])
const activeLiveLineKey = ref('')
const activeLiveError = ref('')
const livePlayerLoading = ref(false)
const showLiveLineSelector = ref(false)
let liveTextTimer: ReturnType<typeof setInterval> | null = null

const thirdPartyLiveUrl = computed(() => String(match.value?.live_url || '').trim())
const liveList = computed<MatchLiveLineItem[]>(() => {
    return Array.isArray(match.value?.live_list) ? match.value.live_list : []
})

const liveSourceText = computed(() => {
    const raw = match.value?.living_tv ?? match.value?.live_source ?? match.value?.livingTv ?? ''
    if (Array.isArray(raw)) {
        return raw
            .map((item: any) => {
                if (typeof item === 'string') return item.trim()
                if (!item || typeof item !== 'object') return ''
                return String(item.live_tag || item.name || item.title || item.source_name || item.label || '').trim()
            })
            .filter(Boolean)
            .join('、')
    }
    return String(raw || '').trim()
})

const tabList = [
    { key: 'live', label: '文字直播' },
    { key: 'data', label: '比赛数据' },
    { key: 'odds', label: '赔率' },
    { key: 'lineup', label: '阵容' },
    { key: 'recent', label: '近期战绩' },
    { key: 'ai', label: 'AI分析' },
]
const showLegacyMatchOdds = false
const activeTab = ref('live')
const lineupList = ref<any[]>([])
const homeStarters = computed(() => lineupList.value.filter((p: any) => p.team_side === 1 && p.is_starter === 1))
const homeSubs = computed(() => lineupList.value.filter((p: any) => p.team_side === 1 && p.is_starter === 0))
const awayStarters = computed(() => lineupList.value.filter((p: any) => p.team_side === 2 && p.is_starter === 1))
const awaySubs = computed(() => lineupList.value.filter((p: any) => p.team_side === 2 && p.is_starter === 0))

const normalizeLiveText = (value: unknown) => String(value || '').trim()

const getLiveFetchStatusText = (value: unknown) => {
    const text = normalizeLiveText(value)
    if (!text) return ''
    const normalized = text.toLowerCase()
    if (normalized === 'pending' || normalized === '0') return '待抓取'
    if (normalized === 'success' || normalized === '1') return '已抓取'
    if (normalized === 'failed' || normalized === 'error' || normalized === '2') return '抓取失败'
    return text
}

const getLiveLineTitle = (item: MatchLiveLineItem) => {
    return (
        normalizeLiveText(item?.title) ||
        normalizeLiveText(item?.name) ||
        normalizeLiveText(item?.label) ||
        normalizeLiveText(item?.live_tag) ||
        normalizeLiveText(item?.source_name) ||
        '直播线路'
    )
}

const formatLiveLineUpdate = (value: unknown) => {
    const text = normalizeLiveText(value)
    if (!text) return ''
    const hhmmss = text.match(/(\d{2}:\d{2}:\d{2})$/)
    if (hhmmss) return hhmmss[1]
    const hhmm = text.match(/(\d{2}:\d{2})$/)
    if (hhmm) return hhmm[1]
    if (/^\d{10,13}$/.test(text)) {
        const raw = text.length === 13 ? Number(text) : Number(text) * 1000
        return formatLiveTime(raw / 1000)
    }
    return text
}

const getLiveLineMeta = (item: MatchLiveLineItem) => {
    const parts = [
        getLiveFetchStatusText(item?.fetch_status),
        formatLiveLineUpdate(item?.last_fetch_at || item?.update_time),
    ].filter(Boolean)
    return parts.length ? parts.join(' · ') : '点击选择直播线路'
}

const getLiveLineKey = (item: MatchLiveLineItem, index: number) => {
    return normalizeLiveText(item?.id) || `${getLiveLineTitle(item)}-${index}`
}

const collectLiveCandidateUrls = (item: MatchLiveLineItem) => {
    const candidates: string[] = []
    const seen = new Set<string>()
    const push = (value: unknown) => {
        const url = normalizeLiveText(value)
        if (!url || seen.has(url)) return
        seen.add(url)
        candidates.push(url)
    }

    push(item?.default_play_url)
    if (Array.isArray(item?.stream_options)) {
        item.stream_options.forEach((option) => {
            push(option?.default_play_url)
            push(option?.play_url_m3u8)
            push(option?.play_url_hd_m3u8)
            push(option?.play_url)
            push(option?.url)
            push(option?.live_url)
            push(option?.play_url_flv)
            push(option?.play_url_hd_flv)
        })
    }
    push(item?.play_url_m3u8)
    push(item?.play_url_hd_m3u8)
    push(item?.play_url)
    push(item?.live_url)
    push(item?.play_url_flv)
    push(item?.play_url_hd_flv)

    return candidates
}

const isInlinePlayableUrl = (url: string) => {
    return /\.(m3u8|mp4)(\?|$)/i.test(url)
}

const resolveLivePlayUrl = (item: MatchLiveLineItem) => {
    return collectLiveCandidateUrls(item).find((url) => isInlinePlayableUrl(url)) || ''
}

const resolveLiveSourceUrl = (item: MatchLiveLineItem) => {
    return (
        normalizeLiveText(item?.source_url) ||
        normalizeLiveText(item?.live_url) ||
        thirdPartyLiveUrl.value
    )
}

const resolvedLiveList = computed<MatchDetailLiveLine[]>(() => {
    return liveList.value.map((item, index) => {
        const playUrl = resolveLivePlayUrl(item)
        return {
            ...item,
            lineKey: getLiveLineKey(item, index),
            displayTitle: getLiveLineTitle(item),
            metaText: getLiveLineMeta(item),
            playUrl,
            sourceUrl: resolveLiveSourceUrl(item),
            hasDirectPlay: !!playUrl,
        }
    })
})

const activeLiveLine = computed(() => {
    return (
        resolvedLiveList.value.find((item) => item.lineKey === activeLiveLineKey.value) ||
        resolvedLiveList.value[0] ||
        null
    )
})

const activeLivePlayUrl = computed(() => activeLiveLine.value?.playUrl || '')
const activeLiveSourceUrl = computed(() => activeLiveLine.value?.sourceUrl || thirdPartyLiveUrl.value)
const activeLiveLineTitle = computed(() => activeLiveLine.value?.displayTitle || '直播线路')
const activeLiveMetaText = computed(() => activeLiveLine.value?.metaText || '')
const activeLivePlayerKey = computed(() => `${activeLiveLine.value?.lineKey || 'live'}-${activeLivePlayUrl.value}`)

const triggerLiveAutoPlay = () => {
    if (!activeLivePlayUrl.value) return
    nextTick(() => {
        setTimeout(() => {
            try {
                const videoContext = uni.createVideoContext('match-live-player')
                videoContext?.play?.()
            } catch (error) {
                console.warn('自动播放直播失败', error)
            }
        }, 80)
    })
}

watch(
    resolvedLiveList,
    (list) => {
        if (!list.length) {
            activeLiveLineKey.value = ''
            activeLiveError.value = ''
            livePlayerLoading.value = false
            showLiveLineSelector.value = false
            return
        }
        if (list.some((item) => item.lineKey === activeLiveLineKey.value)) return
        activeLiveLineKey.value = (list.find((item) => item.hasDirectPlay) || list[0]).lineKey
        activeLiveError.value = ''
    },
    { immediate: true }
)

watch(
    activeLivePlayUrl,
    (url) => {
        activeLiveError.value = ''
        livePlayerLoading.value = !!url
        if (url) {
            triggerLiveAutoPlay()
        }
    },
    { immediate: true }
)

const techStatsList = computed(() => {
    const m = match.value as any
    // 优先使用 tech_stats JSON（兼容所有运动类型）
    let rawList: any[] | null = null
    if (m.tech_stats) {
        try {
            rawList = typeof m.tech_stats === 'string' ? JSON.parse(m.tech_stats) : m.tech_stats
        } catch (e) {
            rawList = null
        }
    }
    if (!rawList || rawList.length === 0) return []
    return rawList.map((item: any) => {
        const h = Number(item.home) || 0
        const a = Number(item.away) || 0
        const total = h + a || 1
        const isPercent = String(item.type).includes('率')
        return {
            label: item.type,
            home: isPercent ? h + '%' : h,
            away: isPercent ? a + '%' : a,
            homePct: isPercent ? h : Math.round((h / total) * 100),
            awayPct: isPercent ? a : Math.round((a / total) * 100),
        }
    })
})

const measureContentHeight = () => {
    nextTick(() => {
        const sysInfo = uni.getSystemInfoSync()
        const windowH = sysInfo.windowHeight || 667
        uni.createSelectorQuery()
            .select('.detail-header')
            .boundingClientRect((rect: any) => {
                const headerH = rect?.height || (statusBarHeight.value + 120)
                contentHeight.value = windowH - headerH
            })
            .exec()
    })
}

uni.getSystemInfo({
    success: (res) => {
        // #ifdef APP-PLUS || MP
        statusBarHeight.value = res.statusBarHeight || 44
        // #endif
        // #ifdef H5
        statusBarHeight.value = 0
        // #endif
        measureContentHeight()
    }
})

onMounted(() => {
    measureContentHeight()
})


const fetchDetail = async (id: number) => {
    loading.value = true
    activeLiveError.value = ''
    try {
        const data = await getMatchDetail({ id })
        match.value = data || {}
        if (data?.live_text?.length) {
            liveTextList.value = data.live_text
        }
        if (data?.status === 1 && data?.match_id) {
            startLiveTextPolling(data.match_id)
        }
        if (data?.match_id) {
            fetchLineup(data.match_id)
        }
    } catch (e) {
        console.error('获取赛事详情失败', e)
        uni.showToast({ title: '获取详情失败', icon: 'none' })
    } finally {
        loading.value = false
    }
}

const startLiveTextPolling = (matchId: number) => {
    if (liveTextTimer) clearInterval(liveTextTimer)
    liveTextTimer = setInterval(async () => {
        try {
            const lastMsgId = liveTextList.value.length > 0
                ? Math.max(...liveTextList.value.map((i: any) => i.msg_id || 0))
                : 0
            const res = await getMatchLiveText({ match_id: matchId, last_msg_id: lastMsgId })
            if (res?.list?.length) {
                liveTextList.value = [...liveTextList.value, ...res.list]
            }
        } catch (e) {
            // ignore
        }
    }, 30000)
}

const stopLiveTextPolling = () => {
    if (liveTextTimer) {
        clearInterval(liveTextTimer)
        liveTextTimer = null
    }
}

const fetchLineup = async (matchId: number) => {
    try {
        const res = await getMatchLineup({ match_id: matchId })
        if (res?.list?.length) {
            lineupList.value = res.list
        }
    } catch (e) {
        // ignore
    }
}

const navigateToLiveWebview = (url: string) => {
    if (!url) {
        uni.showToast({ title: '暂无直播链接', icon: 'none' })
        return
    }
    uni.navigateTo({ url: `/pages/webview/webview?url=${encodeURIComponent(url)}` })
}

const openThirdPartyLive = () => {
    navigateToLiveWebview(thirdPartyLiveUrl.value)
}

const selectLiveLine = (item: MatchDetailLiveLine) => {
    activeLiveLineKey.value = item.lineKey
    activeLiveError.value = ''
    livePlayerLoading.value = !!item.playUrl
    showLiveLineSelector.value = false
    if (item.playUrl) {
        triggerLiveAutoPlay()
    }
}

const toggleLiveLineSelector = () => {
    if (!resolvedLiveList.value.length) {
        uni.showToast({ title: '暂无直播线路', icon: 'none' })
        return
    }
    showLiveLineSelector.value = !showLiveLineSelector.value
}

const openActiveLiveSource = () => {
    navigateToLiveWebview(activeLiveSourceUrl.value)
}

const openLiveFullscreen = () => {
    if (!activeLivePlayUrl.value) {
        uni.showToast({ title: '暂无可全屏播放的视频', icon: 'none' })
        return
    }
    nextTick(() => {
        try {
            const videoContext = uni.createVideoContext('match-live-player')
            videoContext?.requestFullScreen?.({
                direction: 90,
            })
            videoContext?.play?.()
        } catch (error) {
            console.warn('进入全屏播放失败', error)
            uni.showToast({ title: '当前设备暂不支持全屏', icon: 'none' })
        }
    })
}

const handleLivePlayerError = () => {
    livePlayerLoading.value = false
    activeLiveError.value = '当前线路播放失败，可切换其他线路或打开源站继续观看'
}

const handleLivePlayerWaiting = () => {
    if (!activeLivePlayUrl.value) return
    livePlayerLoading.value = true
}

const handleLivePlayerLoaded = () => {
    livePlayerLoading.value = false
}

const handleLivePlayerPlay = () => {
    livePlayerLoading.value = false
}

const formatLiveTime = (ts: any) => {
    if (!ts) return ''
    const s = String(ts)
    const dtMatch = s.match(/(\d{2}):(\d{2}):(\d{2})\s*$/)
    if (dtMatch) return `${dtMatch[1]}:${dtMatch[2]}:${dtMatch[3]}`
    if (/^\d{9,}$/.test(s)) {
        const d = new Date(Number(s) * 1000)
        const hh = String(d.getHours()).padStart(2, '0')
        const mm = String(d.getMinutes()).padStart(2, '0')
        const ss = String(d.getSeconds()).padStart(2, '0')
        return `${hh}:${mm}:${ss}`
    }
    return s
}

const previewLiveImage = (url: string) => {
    uni.previewImage({ urls: [url], current: url })
}

const goBack = () => {
    uni.navigateBack()
}

const goAiAnalysis = () => {
    const id = match.value?.id
    if (!id) return
    uni.navigateTo({ url: `/pages/ai_analysis/ai_analysis?type=match&id=${id}` })
}

const eventTypeMap: Record<number, string> = {
    1: '进球', 2: '黄牌', 3: '红牌', 4: '换人', 5: '点球', 6: '乌龙球', 7: '助攻'
}
const eventTypeText = (type: number) => eventTypeMap[type] || '事件'

const eventQuarter = (minute: string | number) => {
    const m = Number(minute)
    if (m <= 12) return 'Q1'
    if (m <= 24) return 'Q2'
    if (m <= 36) return 'Q3'
    return 'Q4'
}

const eventColorMap: Record<number, string> = {
    1: 'green', 2: 'yellow', 3: 'red', 4: 'blue', 5: 'green', 6: 'red', 7: 'blue'
}
const eventColor = (type: number) => eventColorMap[type] || 'gray'

const resultMap: Record<string, string> = { W: '胜', D: '平', L: '负' }
const resultText = (r: string) => resultMap[r] || r

const formatTs = (ts: number) => {
    if (!ts) return ''
    const d = new Date(ts * 1000)
    const m = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    return `${m}-${day}`
}

const formatMatchTime = (ts: number) => {
    if (!ts) return ''
    const d = getLocalMatchDate(ts, match.value)
    if (!d) return ''
    const y = d.getFullYear()
    const m = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    const h = String(d.getHours()).padStart(2, '0')
    const min = String(d.getMinutes()).padStart(2, '0')
    return `${y}-${m}-${day} ${h}:${min}`
}

const checkAndLoadAi = async (matchId: number) => {
    try {
        const res = await checkAiUnlock({ match_id: matchId })
        if (res.unlocked) {
            aiUnlocked.value = true
            loadInlineAi(matchId)
        }
        if (res.remain_count !== undefined) {
            freeRemain.value = res.remain_count
        }
    } catch (e) {
        // 未登录等情况忽略
    }
}

const loadInlineAi = async (matchId: number) => {
    aiInlineLoading.value = true
    const sections = ['prediction', 'factors', 'odds', 'summary'] as const
    for (const s of sections) {
        try {
            const res = await getMatchPredictSection({ match_id: matchId, section: s })
            aiInline.value[s] = res.data || {}
            if (res.remain_count !== undefined) {
                freeRemain.value = Number(res.remain_count)
            }
        } catch (e) {
            // 忽略单section失败
        }
    }
    aiInlineLoading.value = false
}

onLoad((options) => {
    const id = Number(options?.id || 0)
    if (id > 0) {
        fetchDetail(id)
        checkAndLoadAi(id)
    } else {
        uni.showToast({ title: '参数错误', icon: 'none' })
        setTimeout(() => uni.navigateBack(), 1500)
    }
})

onUnload(() => {
    stopLiveTextPolling()
})
</script>

<style lang="scss" scoped>
.match-detail {
    min-height: 100vh;
    background: #f5f5f5;
}

.detail-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
    gap: 20rpx;
    color: #999;
    font-size: 26rpx;
}

.detail-content {
    padding-bottom: 40rpx;
}

.match-info-wrap {
    margin: 24rpx;
}

.upcoming-card {
    background: #fff;
    border-radius: 24rpx;
    padding: 32rpx;

    &__header {
        margin-bottom: 24rpx;
    }

    &__tags {
        display: flex;
        align-items: center;
        gap: 8rpx;
        flex-wrap: wrap;
    }

    &__league {
        font-size: 24rpx;
        color: #808080;
    }

    &__tag {
        padding: 2rpx 10rpx;
        border-radius: 6rpx;
        font-size: 22rpx;

        &--blue {
            background: #e5edff;

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

    &__hot {
        width: 44rpx;
        height: 42rpx;
        border-radius: 10rpx;
        background: #d84293;
        display: flex;
        align-items: center;
        justify-content: center;

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

    &__teams {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 16rpx 0;
    }

    &__team {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 12rpx;
    }

    &__icon {
        width: 64rpx;
        height: 64rpx;
    }

    &__name {
        font-size: 28rpx;
        font-weight: 600;
        color: #000;
        text-align: center;
    }

    &__center {
        display: flex;
        align-items: center;
        gap: 12rpx;
        flex-shrink: 0;
        padding: 0 16rpx;
    }

    &__score {
        font-size: 40rpx;
        font-weight: 700;
        color: #000;
    }

    &__vs {
        font-size: 24rpx;
        color: #808080;
    }

    &__divider {
        height: 2rpx;
        background: #f2f2f2;
        margin: 16rpx 0;
    }

    &__footer {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 8rpx;
    }

    &__status {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        height: 50rpx;
        padding: 0 24rpx;
        border-radius: 25rpx;
        background: #e5edff;

        text {
            font-size: 24rpx;
            color: #185dff;
            font-weight: 500;
        }
    }

    &__time {
        font-size: 24rpx;
        color: #808080;
    }
}

.match-section {
    margin: 24rpx;
    padding: 32rpx;
    background: #fff;
    border-radius: 16rpx;

    &__title {
        font-size: 30rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 24rpx;
        padding-left: 16rpx;
        border-left: 6rpx solid #185dff;

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

.match-odds {
    display: flex;
    justify-content: space-around;

    &__item {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 12rpx;
    }

    &__label {
        font-size: 24rpx;
        color: #808080;
    }

    &__value {
        font-size: 36rpx;
        font-weight: 600;
        color: #185dff;
    }
}

/* ====== 技术统计条形图 ====== */
.tech-stats {
    &__row {
        margin-bottom: 24rpx;

        &:last-child {
            margin-bottom: 0;
        }
    }

    &__nums {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 8rpx;
    }

    &__home-val,
    &__away-val {
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
        min-width: 60rpx;
    }

    &__home-val {
        text-align: left;
    }

    &__away-val {
        text-align: right;
    }

    &__label {
        font-size: 24rpx;
        color: #999;
        flex: 1;
        text-align: center;
    }

    &__bars {
        display: flex;
        height: 8rpx;
        border-radius: 4rpx;
        overflow: hidden;
        background: #f0f0f0;
    }

    &__bar {
        height: 100%;
        transition: width 0.3s;

        &--home {
            background: #3b82f6;
            border-radius: 4rpx 0 0 4rpx;
        }

        &--away {
            background: #ef4444;
            border-radius: 0 4rpx 4rpx 0;
            margin-left: auto;
        }
    }
}

.match-stats {
    &__row {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 20rpx 0;
        border-bottom: 1rpx solid #f5f5f5;

        &:last-child {
            border-bottom: none;
        }
    }

    &__label {
        flex: 1;
        text-align: center;
        font-size: 26rpx;
        color: #666;
    }

    &__value {
        font-size: 28rpx;
        font-weight: 500;
        color: #333;
    }

    &__home,
    &__away {
        width: 80rpx;
        text-align: center;
        font-size: 28rpx;
        font-weight: 600;
        color: #333;

        &--red {
            color: #185dff;
        }
    }
}

.match-ai {
    display: flex;
    align-items: center;
    padding: 28rpx;
    background: linear-gradient(135deg, #19E1FE, #EC10D5);
    border-radius: 16rpx;
    gap: 20rpx;

    &__badge {
        width: 72rpx;
        height: 72rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(255, 255, 255, 0.25);
        border-radius: 16rpx;
        font-size: 28rpx;
        font-weight: 900;
        color: #fff;
        letter-spacing: 2rpx;
        flex-shrink: 0;
    }

    &__content {
        flex: 1;
    }

    &__title {
        font-size: 30rpx;
        font-weight: 600;
        color: #fff;
        display: block;
    }

    &__desc {
        font-size: 22rpx;
        color: rgba(255, 255, 255, 0.75);
        margin-top: 8rpx;
        display: block;
    }

    &__arrow {
        width: 48rpx;
        height: 48rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(255, 255, 255, 0.2);
        border-radius: 50%;
        flex-shrink: 0;

        text {
            font-size: 36rpx;
            color: #fff;
            font-weight: bold;
        }
    }

    &__vip-info {
        display: flex;
        align-items: center;
        gap: 10rpx;
        margin-top: 16rpx;
        padding: 12rpx 20rpx;
        background: #e5edff;
        border-radius: 12rpx;
    }

    &__vip-tag {
        font-size: 20rpx;
        font-weight: 600;
        color: #fff;
        background: #4d83ff;
        padding: 4rpx 12rpx;
        border-radius: 6rpx;

        &--vip {
            background: linear-gradient(135deg, #f59e0b, #d97706);
        }
    }

    &__vip-text {
        font-size: 24rpx;
        color: #4d83ff;
    }
}

.match-events {
    &__badge {
        width: 40rpx;
        height: 42rpx;
        border-radius: 24rpx;
        background: #185dff;
        display: flex;
        align-items: center;
        justify-content: center;

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

    &__item {
        display: flex;
        padding: 16rpx 0;
    }

    &__time {
        display: flex;
        align-items: center;
        gap: 4rpx;
        flex-shrink: 0;
        padding-top: 4rpx;
    }

    &__quarter {
        font-size: 24rpx;
        color: #808080;
    }

    &__dot {
        width: 16rpx;
        height: 16rpx;
        border-radius: 12rpx;

        &--green {
            background: #00c161;
        }

        &--yellow {
            background: #ff9300;
        }

        &--red {
            background: #f93b37;
        }

        &--blue {
            background: #185dff;
        }

        &--gray {
            background: #999;
        }
    }

    &__info {
        flex: 1;
        padding-left: 16rpx;
    }

    &__header {
        display: flex;
        align-items: center;
        gap: 12rpx;
        margin-bottom: 4rpx;
    }

    &__type {
        font-size: 28rpx;
        font-weight: 600;
        color: #000;
    }

    &__side {
        font-size: 22rpx;
        padding: 2rpx 12rpx;
        border-radius: 6rpx;

        &--home {
            background: #e5edff;
            color: #185dff;
        }

        &--away {
            background: #ffe5e5;
            color: #ee3835;
        }
    }

    &__player {
        font-size: 28rpx;
        color: #000;
        display: block;
        margin-bottom: 2rpx;
    }

    &__desc {
        font-size: 24rpx;
        color: #808080;
        display: block;
    }
}

.match-history {
    &__item {
        display: flex;
        align-items: center;
        padding: 16rpx 0;
    }

    &__date {
        width: 80rpx;
        font-size: 24rpx;
        color: #808080;
        flex-shrink: 0;
    }

    &__teams {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 12rpx;
    }

    &__team {
        font-size: 28rpx;
        color: #000;
        flex: 1;
        text-align: center;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    &__score {
        font-size: 36rpx;
        font-weight: 700;
        color: #185dff;
        min-width: 80rpx;
        text-align: center;
        flex-shrink: 0;
    }

    &__league {
        width: 80rpx;
        font-size: 24rpx;
        color: #808080;
        text-align: right;
        flex-shrink: 0;
    }
}

.match-recent {
    &__team-header {
        display: flex;
        align-items: center;
        gap: 8rpx;
        margin-bottom: 16rpx;
    }

    &__team-icon {
        width: 40rpx;
        height: 40rpx;
        flex-shrink: 0;
    }

    &__team-title {
        font-size: 28rpx;
        font-weight: 600;
        color: #000;
    }

    &__item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 52rpx;
        margin-bottom: 12rpx;

        &:last-child {
            margin-bottom: 0;
        }
    }

    &__left {
        display: flex;
        align-items: center;
        gap: 8rpx;
    }

    &__result {
        width: 52rpx;
        height: 52rpx;
        border-radius: 12rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24rpx;
        font-weight: 600;
        color: #fff;
        flex-shrink: 0;

        &--W {
            background: #00c161;
        }

        &--D {
            background: #ff9300;
        }

        &--L {
            background: #f93b37;
        }
    }

    &__vs {
        font-size: 22rpx;
        color: #808080;
    }

    &__opponent {
        font-size: 28rpx;
        color: #000;
    }

    &__right {
        display: flex;
        align-items: center;
        gap: 16rpx;
    }

    &__score {
        display: flex;
        align-items: center;
    }

    &__score-num {
        font-size: 28rpx;
        color: #000;
        min-width: 20rpx;
        text-align: center;
    }

    &__score-sep {
        font-size: 28rpx;
        color: #000;
        margin: 0 4rpx;
    }

    &__date {
        font-size: 24rpx;
        color: #808080;
        flex-shrink: 0;
    }
}

.match-ai-inline {
    padding: 20rpx 0;

    &__row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12rpx 0;
        border-bottom: 1rpx solid #f0f0f0;
    }

    &__label {
        font-size: 26rpx;
        color: #666;
    }

    &__val {
        font-size: 26rpx;
        color: #333;
        font-weight: 600;

        &--highlight {
            color: #667eea;
            font-weight: 700;
        }
    }

    &__reasoning {
        padding: 16rpx 0;
        font-size: 24rpx;
        color: #888;
        line-height: 1.6;
    }

    &__tags {
        padding: 16rpx 0;
    }

    &__tag-wrap {
        display: flex;
        flex-wrap: wrap;
        gap: 12rpx;
        margin-top: 12rpx;
    }

    &__tag {
        font-size: 22rpx;
        padding: 6rpx 16rpx;
        border-radius: 20rpx;
        background: #f0f0f0;
        color: #666;

        &--green {
            background: rgba(16, 185, 129, 0.1);
            color: #10b981;
        }
    }

    &__summary {
        padding: 16rpx 0;
        font-size: 24rpx;
        color: #555;
        line-height: 1.7;
    }

    &__loading {
        padding: 24rpx 0;
        text-align: center;
        font-size: 24rpx;
        color: #999;
    }

    &__more {
        margin-top: 16rpx;
        text-align: center;
        padding: 16rpx 0;
        background: linear-gradient(135deg, #185dff, #2f80ff);
        border-radius: 12rpx;
        color: #fff;
        font-size: 26rpx;
        font-weight: 600;
    }
}

.match-section__badge {
    display: inline;
}

.live-text {
    &__live-badge {
        display: flex;
        align-items: center;
        gap: 8rpx;
        color: #ef4444;
        font-size: 22rpx;
        font-weight: 600;
    }

    &__live-dot {
        width: 12rpx;
        height: 12rpx;
        border-radius: 50%;
        background: #ef4444;
        animation: live-pulse 1.5s ease-in-out infinite;
    }

    &__item {
        display: flex;
        gap: 16rpx;
        padding: 16rpx 0;
        border-bottom: 1rpx solid #f0f0f0;

        &:last-child {
            border-bottom: none;
        }
    }

    &__left {
        flex-shrink: 0;
    }

    &__avatar {
        width: 56rpx;
        height: 56rpx;
        border-radius: 50%;
        background: #e5e7eb;

        &--default {
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24rpx;
            color: #9ca3af;
            font-weight: 600;
        }
    }

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

    &__meta {
        display: flex;
        align-items: center;
        gap: 12rpx;
        margin-bottom: 6rpx;
    }

    &__name {
        font-size: 24rpx;
        color: #374151;
        font-weight: 600;
    }

    &__time {
        font-size: 22rpx;
        color: #9ca3af;
    }

    &__msg {
        font-size: 26rpx;
        color: #1f2937;
        line-height: 1.5;
        word-break: break-all;
    }

    &__image {
        margin-top: 8rpx;
        max-width: 400rpx;
        border-radius: 8rpx;
    }

    &__empty {
        padding: 40rpx 0;
        text-align: center;
        font-size: 26rpx;
        color: #9ca3af;
    }
}

.live-entrance {
    margin: 0 24rpx 24rpx;
    display: flex;
    flex-direction: column;
    gap: 16rpx;

    &__player-card {
        padding: 24rpx;
        border-radius: 28rpx;
        background: linear-gradient(180deg, #ffffff 0%, #eef4ff 100%);
        box-shadow: 0 18rpx 40rpx rgba(15, 23, 42, 0.08);
        display: flex;
        flex-direction: column;
        gap: 18rpx;
    }

    &__player-header {
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        gap: 16rpx;
    }

    &__player-title-wrap {
        min-width: 0;
        display: flex;
        flex-direction: column;
        gap: 6rpx;
        flex: 1;
    }

    &__player-title {
        font-size: 30rpx;
        font-weight: 700;
        color: #0f172a;
    }

    &__player-meta {
        font-size: 22rpx;
        color: #64748b;
        line-height: 1.5;
    }

    &__player-actions {
        display: flex;
        align-items: center;
        gap: 12rpx;
        flex-wrap: wrap;
        flex-shrink: 0;
    }

    &__player-wrap {
        position: relative;
        border-radius: 24rpx;
        overflow: hidden;
        background: #020617;
    }

    &__player {
        width: 100%;
        height: 420rpx;
        background: #020617;
    }

    &__player-loading {
        position: absolute;
        inset: 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 18rpx;
        background: rgba(2, 6, 23, 0.62);
        z-index: 2;
    }

    &__player-loading-text {
        font-size: 24rpx;
        color: #fff;
        font-weight: 600;
        letter-spacing: 1rpx;
    }

    &__selector {
        display: flex;
        flex-direction: column;
        gap: 14rpx;
        padding-top: 4rpx;
    }

    &__selector-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 18rpx;
        padding: 22rpx 20rpx;
        border-radius: 22rpx;
        background: rgba(15, 23, 42, 0.04);
        border: 2rpx solid transparent;

        &--active {
            background: rgba(24, 93, 255, 0.08);
            border-color: rgba(24, 93, 255, 0.28);
        }
    }

    &__selector-main {
        min-width: 0;
        flex: 1;
        display: flex;
        align-items: center;
        gap: 16rpx;
    }

    &__selector-index {
        width: 56rpx;
        height: 56rpx;
        border-radius: 16rpx;
        background: #0f172a;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;

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

    &__selector-content {
        min-width: 0;
        display: flex;
        flex-direction: column;
        gap: 6rpx;
    }

    &__selector-title {
        font-size: 28rpx;
        font-weight: 700;
        color: #0f172a;
    }

    &__selector-desc {
        font-size: 22rpx;
        color: #64748b;
        line-height: 1.5;
    }

    &__selector-tag {
        flex-shrink: 0;
        font-size: 22rpx;
        color: #185dff;
        font-weight: 600;
    }

    &__player-empty {
        min-height: 240rpx;
        border-radius: 24rpx;
        background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 40rpx 32rpx;
        text-align: center;
        gap: 12rpx;
    }

    &__empty-action {
        margin-top: 10rpx;
    }

    &__player-empty-title {
        font-size: 28rpx;
        font-weight: 700;
        color: #fff;
    }

    &__player-empty-desc {
        font-size: 22rpx;
        line-height: 1.6;
        color: rgba(255, 255, 255, 0.72);
    }

    &__player-error {
        font-size: 22rpx;
        color: #dc2626;
        line-height: 1.5;
    }

    &__fallback-card {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 20rpx;
        padding: 28rpx;
        border-radius: 24rpx;
        background: linear-gradient(135deg, #0f172a 0%, #1d4ed8 100%);
        box-shadow: 0 16rpx 36rpx rgba(29, 78, 216, 0.18);
    }

    &__left {
        display: flex;
        align-items: center;
        gap: 18rpx;
        min-width: 0;
        flex: 1;
    }

    &__badge {
        width: 76rpx;
        height: 76rpx;
        border-radius: 22rpx;
        background: rgba(255, 255, 255, 0.16);
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;

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

    &__content {
        min-width: 0;
        display: flex;
        flex-direction: column;
        gap: 6rpx;
    }

    &__title {
        font-size: 30rpx;
        font-weight: 700;
        color: #fff;
    }

    &__desc {
        font-size: 24rpx;
        color: rgba(255, 255, 255, 0.82);
        line-height: 1.45;
    }

    &__action {
        display: flex;
        align-items: center;
        gap: 6rpx;
        font-size: 26rpx;
        font-weight: 600;
        color: #c7d2fe;
        flex-shrink: 0;
    }
}

@keyframes live-pulse {

    0%,
    100% {
        opacity: 1;
    }

    50% {
        opacity: 0.3;
    }
}

/* ====== Tab 导航栏 ====== */
.detail-tabs {
    width: 100%;
    white-space: nowrap;
    background: #fff;
    border-bottom: 1rpx solid #f0f0f0;
    box-sizing: border-box;

    &__inner {
        min-width: 100%;
        padding: 0 24rpx;
        display: inline-flex;
        align-items: stretch;
        justify-content: space-between;
        gap: 32rpx;
        box-sizing: border-box;
    }

    &__item {
        position: relative;
        flex: 0 0 auto;
        padding: 20rpx 0;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        font-size: 26rpx;
        color: #999;
        white-space: nowrap;
        transition: color 0.2s;

        &--active {
            color: #185dff;
            font-weight: 600;

            &::after {
                content: '';
                position: absolute;
                bottom: 0;
                left: 50%;
                transform: translateX(-50%);
                width: 40rpx;
                height: 4rpx;
                border-radius: 2rpx;
                background: #185dff;
            }
        }
    }

    &__dot {
        position: absolute;
        top: 18rpx;
        right: -14rpx;
        width: 10rpx;
        height: 10rpx;
        border-radius: 50%;
        background: #ef4444;
        animation: live-pulse 1.5s ease-in-out infinite;
    }
}

/* ====== Tab 内容区 ====== */
.detail-tab-body {
    flex: 1;
    overflow: hidden;
}

.detail-tab-scroll {
    height: 100%;
    padding: 20rpx 24rpx;
    box-sizing: border-box;
}

/* ====== Tab 卡片通用 ====== */
.tab-card {
    background: #fff;
    border-radius: 16rpx;
    padding: 24rpx;
    margin-bottom: 20rpx;

    &__title {
        display: flex;
        align-items: center;
        gap: 10rpx;
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 20rpx;
    }

    &__team-icon {
        width: 36rpx;
        height: 36rpx;
    }

    &__badge {
        font-size: 20rpx;
        padding: 4rpx 12rpx;
        border-radius: 16rpx;
        background: #f0f0f0;
        color: #666;

        &--green {
            background: rgba(16, 185, 129, 0.1);
            color: #10b981;
        }
    }
}

/* ====== 阵容 ====== */
.lineup-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
}

.lineup-player {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 120rpx;

    &__avatar {
        width: 72rpx;
        height: 72rpx;
        border-radius: 50%;
        background: #e5e7eb;
        margin-bottom: 6rpx;

        &--default {
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24rpx;
            color: #666;
            font-weight: 700;
        }
    }

    &__name {
        font-size: 22rpx;
        color: #333;
        text-align: center;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        max-width: 120rpx;
    }

    &__pos {
        font-size: 20rpx;
        color: #999;
    }
}
</style>
