<template>
    <view class="ai-page">
        <!-- 自定义导航栏 -->
        <view class="ai-nav" :style="{ paddingTop: statusBarHeight + 'px' }">
            <view class="ai-nav__inner">
                <view class="ai-nav__back" @tap="goBack">
                    <u-icon name="arrow-left" size="36" color="#fff" />
                </view>
                <text class="ai-nav__title">AI智能分析</text>
                <view class="ai-nav__placeholder" />
            </view>
        </view>

        <scroll-view scroll-y class="ai-scroll" :style="{ height: contentHeight + 'px' }">
            <!-- 赛事信息卡片 -->
            <view v-if="analysisType === 'match' && matchInfo.home_team" class="ai-match-card">
                <view class="ai-match-card__teams">
                    <text class="ai-match-card__team">{{ matchInfo.home_team }}</text>
                    <text class="ai-match-card__vs">VS</text>
                    <text class="ai-match-card__team">{{ matchInfo.away_team }}</text>
                </view>
                <view class="ai-match-card__meta">
                    <text>{{ matchInfo.league }}</text>
                    <text>{{ matchInfo.match_time }}</text>
                </view>
            </view>

            <!-- 资讯信息卡片 -->
            <view v-if="analysisType === 'article' && articleTitle" class="ai-article-card">
                <text class="ai-article-card__title">{{ articleTitle }}</text>
            </view>

            <!-- 帖子信息卡片 -->
            <view v-if="analysisType === 'post' && (postTitle || postMetaText)" class="ai-article-card ai-article-card--post">
                <text class="ai-article-card__eyebrow">社区帖子</text>
                <text class="ai-article-card__title">{{ postTitle || '帖子AI分析' }}</text>
                <text v-if="postMetaText" class="ai-article-card__desc">{{ postMetaText }}</text>
            </view>
            <view v-if="analysisType === 'post' && postImages.length" class="ai-post-images">
                <view class="ai-post-images__head">
                    <text class="ai-post-images__title">原帖图片</text>
                    <text class="ai-post-images__count">{{ postImages.length }} 张</text>
                </view>
                <image
                    v-for="(image, index) in postImages"
                    :key="image"
                    class="ai-post-images__item"
                    :src="image"
                    mode="widthFix"
                    @tap="previewPostImage(index)"
                />
            </view>

            <!-- VIP/免费用户信息 -->
            <view class="ai-vip-bar">
                <view v-if="isVipUser" class="ai-vip-bar__inner ai-vip-bar__inner--vip">
                    <text class="ai-vip-bar__badge">VIP</text>
                    <text class="ai-vip-bar__text">尊贵的{{ vipLevelName }}，您的到期时间为{{ vipExpireDate }}</text>
                </view>
                <view v-else class="ai-vip-bar__inner ai-vip-bar__inner--free">
                    <text class="ai-vip-bar__badge ai-vip-bar__badge--free">免费</text>
                    <text class="ai-vip-bar__text">{{ AI_DAILY_FREE_TEXT }}，今日剩余{{ freeRemain }}次</text>
                </view>
            </view>

            <!-- 加载状态 -->
            <view v-if="loading" class="ai-loading">
                <view class="ai-loading__dots">
                    <view class="ai-loading__dot" v-for="i in 3" :key="i" />
                </view>
                <text class="ai-loading__text">{{ currentLoadingText }}</text>
                <text v-if="showAnalysisTimer" class="ai-loading__timer">分析用时 {{ analysisDurationText }}</text>
                <text class="ai-loading__hint">{{ loadingHintText }}</text>
            </view>

            <!-- 分析结果 - 赛事预测（分段渲染） -->
            <view v-if="analysisType === 'match'" class="ai-result">
                <!-- 预测结果 -->
                <view v-if="predictionData" class="ai-section ai-section--fadein">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">🏆</text>
                        <text class="ai-section__title">预测结果</text>
                    </view>
                    <view class="ai-predict">
                        <view class="ai-predict__main">
                            <text class="ai-predict__result">{{ predictionData.prediction?.result || '待分析' }}</text>
                            <view class="ai-predict__conf">
                                <text>置信度</text>
                                <view class="ai-predict__bar">
                                    <view class="ai-predict__bar-fill"
                                        :style="{ width: (predictionData.prediction?.confidence || 0) + '%' }" />
                                </view>
                                <text class="ai-predict__pct">{{ predictionData.prediction?.confidence || 0 }}%</text>
                            </view>
                        </view>
                        <view class="ai-predict__score">
                            <text class="ai-predict__score-label">预测比分</text>
                            <text class="ai-predict__score-val">{{ predictionData.prediction?.score_predict || '-'
                                }}</text>
                        </view>
                    </view>
                    <text class="ai-predict__reason">{{ streamReasoning }}<text
                            v-if="streamReasoning.length < (predictionData.prediction?.reasoning || '').length"
                            class="ai-cursor">|</text></text>
                </view>

                <!-- 实力对比 -->
                <view v-if="predictionData?.analysis" class="ai-section ai-section--fadein">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">📊</text>
                        <text class="ai-section__title">实力对比</text>
                    </view>
                    <view class="ai-strength">
                        <view class="ai-strength__row">
                            <text>{{ matchInfo.home_team }}</text>
                            <view class="ai-strength__bar">
                                <view class="ai-strength__fill ai-strength__fill--home"
                                    :style="{ width: (predictionData.analysis?.home_strength || 50) + '%' }" />
                            </view>
                            <text>{{ predictionData.analysis?.home_strength || 50 }}</text>
                        </view>
                        <view class="ai-strength__row">
                            <text>{{ matchInfo.away_team }}</text>
                            <view class="ai-strength__bar">
                                <view class="ai-strength__fill ai-strength__fill--away"
                                    :style="{ width: (predictionData.analysis?.away_strength || 50) + '%' }" />
                            </view>
                            <text>{{ predictionData.analysis?.away_strength || 50 }}</text>
                        </view>
                    </view>
                </view>

                <!-- 分段loading提示 -->
                <view v-if="factorsLoading" class="ai-section-loading">
                    <view class="ai-loading__dots">
                        <view class="ai-loading__dot" v-for="i in 3" :key="i" />
                    </view>
                    <text class="ai-section-loading__text">{{ currentLoadingText }}</text>
                    <text v-if="showAnalysisTimer" class="ai-section-loading__time">分析用时 {{ analysisDurationText }}</text>
                </view>

                <!-- 关键因素 -->
                <view v-if="factorsData?.key_factors?.length" class="ai-section ai-section--fadein">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">🔑</text>
                        <text class="ai-section__title">关键因素</text>
                    </view>
                    <view class="ai-tags">
                        <view v-for="(f, i) in factorsData.key_factors" :key="i" class="ai-tag ai-tag--green">
                            <text>{{ f }}</text>
                        </view>
                    </view>
                </view>

                <!-- 风险因素 -->
                <view v-if="factorsData?.risk_factors?.length" class="ai-section ai-section--fadein">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">⚠️</text>
                        <text class="ai-section__title">风险因素</text>
                    </view>
                    <view class="ai-tags">
                        <view v-for="(r, i) in factorsData.risk_factors" :key="i" class="ai-tag ai-tag--red">
                            <text>{{ r }}</text>
                        </view>
                    </view>
                </view>

                <!-- 分段loading提示 -->
                <view v-if="oddsLoading" class="ai-section-loading">
                    <view class="ai-loading__dots">
                        <view class="ai-loading__dot" v-for="i in 3" :key="i" />
                    </view>
                    <text class="ai-section-loading__text">{{ currentLoadingText }}</text>
                    <text v-if="showAnalysisTimer" class="ai-section-loading__time">分析用时 {{ analysisDurationText }}</text>
                </view>

                <!-- 赔率观点 -->
                <view v-if="oddsData?.odds_opinion" class="ai-section ai-section--fadein">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">💰</text>
                        <text class="ai-section__title">赔率观点</text>
                    </view>
                    <view class="ai-odds">
                        <text class="ai-odds__value">推荐：{{ oddsData.odds_opinion.value_bet }}</text>
                        <text class="ai-odds__explain">{{ streamOddsExplain }}<text
                                v-if="streamOddsExplain.length < (oddsData.odds_opinion?.explanation || '').length"
                                class="ai-cursor">|</text></text>
                    </view>
                </view>

                <!-- 分段loading提示 -->
                <view v-if="summaryLoading" class="ai-section-loading">
                    <view class="ai-loading__dots">
                        <view class="ai-loading__dot" v-for="i in 3" :key="i" />
                    </view>
                    <text class="ai-section-loading__text">{{ currentLoadingText }}</text>
                    <text v-if="showAnalysisTimer" class="ai-section-loading__time">分析用时 {{ analysisDurationText }}</text>
                </view>

                <!-- 分析总结 -->
                <view v-if="summaryData?.summary" class="ai-section ai-section--fadein">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">📝</text>
                        <text class="ai-section__title">分析总结</text>
                    </view>
                    <text class="ai-summary">{{ streamSummary }}<text
                            v-if="streamSummary.length < (summaryData.summary || '').length"
                            class="ai-cursor">|</text></text>
                </view>
            </view>

            <!-- 分析结果 - 资讯分析（保持原样） -->
            <view v-if="!loading && analysisData && analysisType === 'article'" class="ai-result">
                <!-- a) 核心摘要 -->
                <view class="ai-section">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">📋</text>
                        <text class="ai-section__title">核心摘要</text>
                    </view>
                    <text class="ai-summary">{{ analysisData.summary }}</text>
                </view>

                <!-- b) 涉及联赛和球队 -->
                <view v-if="analysisData.leagues_and_teams" class="ai-section">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">🏟️</text>
                        <text class="ai-section__title">涉及联赛与球队</text>
                    </view>
                    <view v-if="analysisData.leagues_and_teams.leagues?.length" class="ai-league-row">
                        <text class="ai-league-row__label">联赛</text>
                        <view class="ai-tags">
                            <view v-for="(l, i) in analysisData.leagues_and_teams.leagues" :key="i"
                                class="ai-tag ai-tag--blue">
                                <text>{{ l }}</text>
                            </view>
                        </view>
                    </view>
                    <view v-if="analysisData.leagues_and_teams.teams?.length" class="ai-league-row">
                        <text class="ai-league-row__label">球队</text>
                        <view class="ai-tags">
                            <view v-for="(t, i) in analysisData.leagues_and_teams.teams" :key="i"
                                class="ai-tag ai-tag--green">
                                <text>{{ t }}</text>
                            </view>
                        </view>
                    </view>
                    <view v-if="analysisData.leagues_and_teams.match_context" class="ai-context">
                        <text>{{ analysisData.leagues_and_teams.match_context }}</text>
                    </view>
                </view>

                <!-- c) 近期比赛 & 历史交手 -->
                <view v-if="analysisData.upcoming_matches?.length" class="ai-section">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">�</text>
                        <text class="ai-section__title">近期比赛</text>
                    </view>
                    <view v-for="(m, i) in analysisData.upcoming_matches" :key="i" class="ai-match-item">
                        <view class="ai-match-item__teams">
                            <text class="ai-match-item__home">{{ m.home_team }}</text>
                            <text class="ai-match-item__vs">VS</text>
                            <text class="ai-match-item__away">{{ m.away_team }}</text>
                        </view>
                        <view class="ai-match-item__meta">
                            <text class="ai-match-item__league">{{ m.league }}</text>
                            <text class="ai-match-item__time">{{ m.estimated_time }}</text>
                        </view>
                        <text v-if="m.importance" class="ai-match-item__importance">{{ m.importance }}</text>
                    </view>
                </view>

                <view v-if="analysisData.head_to_head?.available" class="ai-section">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">⚔️</text>
                        <text class="ai-section__title">历史交手记录</text>
                    </view>
                    <view class="ai-h2h-table">
                        <view class="ai-h2h-table__head">
                            <text class="ai-h2h-table__cell ai-h2h-table__cell--date">日期</text>
                            <text class="ai-h2h-table__cell ai-h2h-table__cell--team">主队</text>
                            <text class="ai-h2h-table__cell ai-h2h-table__cell--score">比分</text>
                            <text class="ai-h2h-table__cell ai-h2h-table__cell--team">客队</text>
                        </view>
                        <view v-for="(r, i) in analysisData.head_to_head.records" :key="i" class="ai-h2h-table__row">
                            <text class="ai-h2h-table__cell ai-h2h-table__cell--date">{{ r.date }}</text>
                            <text class="ai-h2h-table__cell ai-h2h-table__cell--team">{{ r.home }}</text>
                            <text class="ai-h2h-table__cell ai-h2h-table__cell--score ai-h2h-table__cell--score-val">{{
                                r.score }}</text>
                            <text class="ai-h2h-table__cell ai-h2h-table__cell--team">{{ r.away }}</text>
                        </view>
                    </view>
                    <text v-if="analysisData.head_to_head.summary" class="ai-h2h-summary">{{
                        analysisData.head_to_head.summary }}</text>
                </view>

                <!-- d) 博彩分析 -->
                <view v-if="analysisData.betting_analysis" class="ai-section">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">💰</text>
                        <text class="ai-section__title">博彩分析</text>
                    </view>
                    <view class="ai-betting">
                        <view class="ai-betting__top">
                            <view class="ai-betting__predict">
                                <text class="ai-betting__result">{{ analysisData.betting_analysis.prediction
                                    }}</text>
                                <view class="ai-betting__conf-row">
                                    <text class="ai-betting__conf-label">置信度</text>
                                    <view class="ai-predict__bar">
                                        <view class="ai-predict__bar-fill"
                                            :style="{ width: (analysisData.betting_analysis.confidence || 0) + '%' }" />
                                    </view>
                                    <text class="ai-predict__pct">{{ analysisData.betting_analysis.confidence || 0
                                        }}%</text>
                                </view>
                            </view>
                            <view class="ai-betting__risk"
                                :class="'ai-betting__risk--' + analysisData.betting_analysis.risk_level">
                                <text class="ai-betting__risk-label">风险</text>
                                <text class="ai-betting__risk-val">{{
                                    riskText(analysisData.betting_analysis.risk_level) }}</text>
                            </view>
                        </view>
                        <text class="ai-betting__reason">{{ analysisData.betting_analysis.reasoning }}</text>
                        <view v-if="analysisData.betting_analysis.key_factors?.length" class="ai-betting__factors">
                            <view v-for="(f, i) in analysisData.betting_analysis.key_factors" :key="i"
                                class="ai-tag ai-tag--green">
                                <text>{{ f }}</text>
                            </view>
                        </view>
                        <view v-if="analysisData.betting_analysis.value_bet" class="ai-betting__value">
                            <text class="ai-betting__value-label">推荐方向</text>
                            <text class="ai-betting__value-text">{{ analysisData.betting_analysis.value_bet
                                }}</text>
                        </view>
                    </view>
                </view>

                <!-- e) 风险提示 -->
                <view v-if="analysisData.risk_warnings?.length" class="ai-section">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">⚠️</text>
                        <text class="ai-section__title">温馨提示</text>
                    </view>
                    <view class="ai-list">
                        <view v-for="(w, i) in analysisData.risk_warnings" :key="i" class="ai-list__item">
                            <text class="ai-list__num">{{ (i as number) + 1 }}</text>
                            <text class="ai-list__text ai-list__text--warn">{{ w }}</text>
                        </view>
                    </view>
                </view>

                <!-- 重点提炼 -->
                <view v-if="analysisData.key_points?.length" class="ai-section">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">🔑</text>
                        <text class="ai-section__title">重点提炼</text>
                    </view>
                    <view class="ai-list">
                        <view v-for="(p, i) in analysisData.key_points" :key="i" class="ai-list__item">
                            <text class="ai-list__num">{{ (i as number) + 1 }}</text>
                            <text class="ai-list__text">{{ p }}</text>
                        </view>
                    </view>
                </view>

                <!-- 反向观点 -->
                <view v-if="analysisData.opposite_views?.length" class="ai-section">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">💡</text>
                        <text class="ai-section__title">反向观点</text>
                    </view>
                    <view class="ai-tags">
                        <view v-for="(v, i) in analysisData.opposite_views" :key="i" class="ai-tag ai-tag--blue">
                            <text>{{ v }}</text>
                        </view>
                    </view>
                </view>

                <!-- 情绪分析 -->
                <view v-if="analysisData.sentiment" class="ai-section">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">🎯</text>
                        <text class="ai-section__title">情绪分析</text>
                    </view>
                    <view class="ai-sentiment">
                        <text class="ai-sentiment__label"
                            :class="'ai-sentiment__label--' + analysisData.sentiment.label">
                            {{ sentimentText }}
                        </text>
                        <text class="ai-sentiment__conf">置信度 {{ analysisData.sentiment.confidence }}%</text>
                    </view>
                </view>

                <!-- 智能标签 -->
                <view v-if="analysisData.tags?.length" class="ai-section">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">🏷️</text>
                        <text class="ai-section__title">智能标签</text>
                    </view>
                    <view class="ai-tags">
                        <view v-for="(t, i) in analysisData.tags" :key="i" class="ai-tag ai-tag--gray">
                            <text>{{ t }}</text>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 分析结果 - 帖子分析 -->
            <view v-if="!loading && analysisData && analysisType === 'post'" class="ai-result">
                <view class="ai-section ai-section--fadein">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">🤖</text>
                        <text class="ai-section__title">综合结论</text>
                    </view>
                    <view class="ai-post-score">
                        <view class="ai-post-score__badge">
                            <text class="ai-post-score__value">{{ analysisData.overall_score || 0 }}</text>
                            <text class="ai-post-score__label">综合评分</text>
                        </view>
                        <text class="ai-post-score__summary">{{ analysisData.summary || '当前帖子可参考信息有限，请谨慎判断。' }}</text>
                    </view>
                </view>

                <view v-if="analysisData.image_interpretation?.length" class="ai-section ai-section--fadein">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">🖼️</text>
                        <text class="ai-section__title">图片解读</text>
                    </view>
                    <view class="ai-list">
                        <view v-for="(item, index) in analysisData.image_interpretation" :key="index" class="ai-list__item">
                            <text class="ai-list__num">{{ (index as number) + 1 }}</text>
                            <text class="ai-list__text">{{ item }}</text>
                        </view>
                    </view>
                </view>

                <view v-if="analysisData.poem_analysis" class="ai-section ai-section--fadein">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">📜</text>
                        <text class="ai-section__title">诗句字谜</text>
                    </view>
                    <text class="ai-section__text">{{ analysisData.poem_analysis }}</text>
                </view>

                <view v-if="analysisData.next_prediction" class="ai-section ai-section--fadein">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">🎯</text>
                        <text class="ai-section__title">下期预测</text>
                    </view>
                    <view v-if="analysisData.next_prediction.recommended_numbers?.length" class="ai-tags">
                        <view v-for="(item, index) in analysisData.next_prediction.recommended_numbers" :key="index" class="ai-tag ai-tag--blue">
                            <text>{{ item }}</text>
                        </view>
                    </view>
                    <text class="ai-post-inline">预测信心 {{ analysisData.next_prediction.confidence || 0 }}%</text>
                    <view v-if="analysisData.next_prediction.reasons?.length" class="ai-list">
                        <view v-for="(item, index) in analysisData.next_prediction.reasons" :key="index" class="ai-list__item">
                            <text class="ai-list__num">{{ (index as number) + 1 }}</text>
                            <text class="ai-list__text">{{ item }}</text>
                        </view>
                    </view>
                </view>

                <view v-if="analysisData.credibility_signals?.length" class="ai-section ai-section--fadein">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">🔎</text>
                        <text class="ai-section__title">可信线索</text>
                    </view>
                    <view class="ai-list">
                        <view v-for="(item, index) in analysisData.credibility_signals" :key="index" class="ai-list__item">
                            <text class="ai-list__num">{{ (index as number) + 1 }}</text>
                            <text class="ai-list__text">{{ item }}</text>
                        </view>
                    </view>
                </view>

                <view v-if="analysisData.risk_warning?.length" class="ai-section ai-section--fadein">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">⚠️</text>
                        <text class="ai-section__title">风险提示</text>
                    </view>
                    <view class="ai-list">
                        <view v-for="(item, index) in analysisData.risk_warning" :key="index" class="ai-list__item">
                            <text class="ai-list__num">{{ (index as number) + 1 }}</text>
                            <text class="ai-list__text ai-list__text--warn">{{ item }}</text>
                        </view>
                    </view>
                </view>

                <view v-if="analysisData.similar_history?.length" class="ai-section ai-section--fadein">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">🗂️</text>
                        <text class="ai-section__title">相似历史</text>
                    </view>
                    <view class="ai-list">
                        <view v-for="(item, index) in analysisData.similar_history" :key="`${item.domain}-${item.source_id}-${index}`" class="ai-list__item">
                            <text class="ai-list__num">{{ (index as number) + 1 }}</text>
                            <view class="ai-post-history">
                                <text class="ai-post-history__title">{{ item.title || `历史样本 #${item.source_id}` }}</text>
                                <text class="ai-post-history__meta">{{ domainText(item.domain) }}<text v-if="item.issue"> · {{ item.issue }}</text></text>
                            </view>
                        </view>
                    </view>
                </view>

                <view v-if="analysisData.evidence_list?.length" class="ai-section ai-section--fadein">
                    <view class="ai-section__header">
                        <text class="ai-section__icon">📚</text>
                        <text class="ai-section__title">证据来源</text>
                    </view>
                    <view v-for="(item, index) in analysisData.evidence_list.slice(0, 4)" :key="`${item.domain}-${item.source_id}-${index}`" class="ai-evidence-card">
                        <view class="ai-evidence-card__meta">
                            <text class="ai-evidence-card__domain">{{ domainText(item.domain) }}</text>
                            <text class="ai-evidence-card__source">ID {{ item.source_id }}</text>
                        </view>
                        <text class="ai-evidence-card__title">{{ item.title || '知识库证据' }}</text>
                        <text v-if="item.content" class="ai-evidence-card__content">{{ item.content }}</text>
                    </view>
                </view>
            </view>

            <!-- 错误状态 -->
            <view v-if="!loading && errorMsg" class="ai-error">
                <text class="ai-error__icon">😔</text>
                <text class="ai-error__text">{{ errorMsg }}</text>
                <view class="ai-error__btn" @tap="retryAnalysis">
                    <text>重新分析</text>
                </view>
            </view>

            <!-- 免责声明 -->
            <view v-if="!loading && (analysisData || hasAnyMatchData)" class="ai-disclaimer">
                <text>声明：AI分析结果仅供参考，不构成任何投资建议。请理性对待分析结果。</text>
            </view>

            <view style="height: 60rpx" />
        </scroll-view>
    </view>
</template>

<script lang="ts" setup>
import { ref, computed, onUnmounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getMatchPredictSection, getArticleAnalysis } from '@/api/ai'
import { getCommunityPostAiAnalysis, getCommunityPostAiAnalysisResult, getCommunityPostDetail } from '@/api/community'
import { useUserStore } from '@/stores/user'
import { AI_DAILY_FREE_TEXT, getAiFreeRemain } from '@/config/ai'

const statusBarHeight = ref(0)
const contentHeight = ref(500)
const loading = ref(true)
const analysisType = ref('match')

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 syncAiRemain = (res: any) => {
    if (res?.remain_count !== undefined) {
        freeRemain.value = Number(res.remain_count)
    }
}

const predictionData = ref<any>(null)
const factorsData = ref<any>(null)
const oddsData = ref<any>(null)
const summaryData = ref<any>(null)

const predictionLoading = ref(false)
const factorsLoading = ref(false)
const oddsLoading = ref(false)
const summaryLoading = ref(false)

const analysisData = ref<any>(null)
const errorMsg = ref('')
const matchInfo = ref<any>({})
const articleTitle = ref('')
const postTitle = ref('')
const postTags = ref<string[]>([])
const postAuthor = ref('')
const postImages = ref<string[]>([])
let refId = 0

const hasAnyMatchData = computed(() => predictionData.value || factorsData.value || oddsData.value || summaryData.value)
const postMetaText = computed(() => {
    const meta: string[] = []
    if (postAuthor.value) {
        meta.push(postAuthor.value)
    }
    if (postTags.value.length) {
        meta.push(postTags.value.slice(0, 3).map(tag => `#${tag}`).join(' '))
    }
    return meta.join(' · ')
})

uni.getSystemInfo({
    success: (res) => {
        // #ifdef APP-PLUS || MP
        statusBarHeight.value = res.statusBarHeight || 44
        // #endif
        // #ifdef H5
        statusBarHeight.value = 0
        // #endif
        const windowH = res.windowHeight || 667
        const headerH = statusBarHeight.value + 44
        contentHeight.value = windowH - headerH
    }
})

const sentimentText = computed(() => {
    const map: Record<string, string> = { positive: '积极', neutral: '中性', negative: '消极' }
    return map[analysisData.value?.sentiment?.label] || '未知'
})

const sectionLoadingText: Record<string, string> = {
    prediction: '正在生成预测结果...',
    factors: '正在分析关键因素...',
    odds: '正在解读赔率数据...',
    summary: '正在撰写分析总结...',
}
const currentLoadingText = ref('AI正在分析中...')
const analysisElapsedSeconds = ref(0)
let analysisTimer: ReturnType<typeof setInterval> | null = null
let isPageAlive = true
const POST_RESULT_POLL_INTERVAL_MS = 5000
const POST_RESULT_POLL_MAX_SECONDS = 120

const streamReasoning = ref('')
const streamOddsExplain = ref('')
const streamSummary = ref('')
let typeTimers: number[] = []
const showAnalysisTimer = computed(() => loading.value || predictionLoading.value || factorsLoading.value || oddsLoading.value || summaryLoading.value)
const analysisDurationText = computed(() => {
    const total = Math.max(0, Number(analysisElapsedSeconds.value || 0))
    const minutes = Math.floor(total / 60)
    const seconds = total % 60
    return `${minutes}m${seconds}s`
})
const loadingHintText = computed(() => {
    if (analysisElapsedSeconds.value >= 60) {
        return '正在结合知识库与模型继续推理，复杂内容可能需要1-3分钟'
    }
    return '基于大数据的智能分析，请稍候'
})

const getRawAnalysisErrorMessage = (error: any) => {
    return typeof error === 'string'
        ? error
        : String(error?.msg || error?.errMsg || error?.message || '')
}

const getAnalysisHttpStatus = (error: any) => {
    return Number(error?.statusCode || error?.status || error?.response?.statusCode || error?.response?.status || 0)
}

const isAnalysisTransportError = (error: any) => {
    const status = getAnalysisHttpStatus(error)
    if ([502, 503, 504].includes(status)) {
        return true
    }
    return /timeout|request:fail|abort|网络|network|Bad Gateway|Service Unavailable|Gateway Timeout|网关/i.test(getRawAnalysisErrorMessage(error))
}

const extractPostAnalysisPacket = (res: any) => {
    const payload = res?.analysis ? res : (res?.data?.analysis ? res.data : null)
    return {
        analysis: payload?.analysis || null,
        fromCache: !!payload?.from_cache
    }
}

const shouldRefreshPostAnalysisCache = (packet: { analysis: any; fromCache: boolean }) => {
    const analysis = packet.analysis || {}
    return packet.fromCache
        && !!analysis.next_prediction
        && analysis.analysis_source !== 'image_free_v1'
}

const getAnalysisErrorMessage = (error: any) => {
    const rawMessage = getRawAnalysisErrorMessage(error)
    const status = getAnalysisHttpStatus(error)

    if ([502, 503, 504].includes(status) || /Bad Gateway|Service Unavailable|Gateway Timeout|网关/i.test(rawMessage)) {
        return 'AI分析服务正在排队或网关暂时断开，请稍后重新进入分析页查看结果'
    }
    if (/timeout|超时/i.test(rawMessage)) {
        return 'AI分析耗时较长，请稍后重新分析；页面已延长等待时间，但当前网络或模型响应仍超时'
    }
    if (/abort/i.test(rawMessage)) {
        return 'AI分析请求已取消，请重新进入分析页后再试'
    }
    if (/request:fail/i.test(rawMessage)) {
        return 'AI分析请求失败，请检查网络后重试；如果刚刚触发过分析，请稍等片刻再打开结果'
    }

    return rawMessage || 'AI分析失败，请稍后重试'
}

const clearTypeTimers = () => {
    typeTimers.forEach(t => clearTimeout(t))
    typeTimers = []
}

const startAnalysisTimer = () => {
    stopAnalysisTimer()
    analysisElapsedSeconds.value = 0
    const startAt = Date.now()
    analysisTimer = setInterval(() => {
        analysisElapsedSeconds.value = Math.floor((Date.now() - startAt) / 1000)
    }, 1000)
}

const stopAnalysisTimer = () => {
    if (analysisTimer) {
        clearInterval(analysisTimer)
        analysisTimer = null
    }
}

const previewPostImage = (index: number) => {
    if (!postImages.value.length) {
        return
    }
    uni.previewImage({
        urls: postImages.value,
        current: postImages.value[index] || postImages.value[0]
    })
}

const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

const waitForPostAnalysisResult = async (postId: number) => {
    const maxAttempts = Math.ceil((POST_RESULT_POLL_MAX_SECONDS * 1000) / POST_RESULT_POLL_INTERVAL_MS)
    let resultEndpointUnavailable = false
    let fallbackRequestCount = 0
    for (let i = 0; i < maxAttempts && isPageAlive; i++) {
        currentLoadingText.value = i === 0
            ? '请求仍在生成，正在等待分析结果...'
            : 'AI仍在生成结果，正在查询缓存...'
        await sleep(POST_RESULT_POLL_INTERVAL_MS)
        if (!isPageAlive) {
            return false
        }

        try {
            const res = await getCommunityPostAiAnalysisResult({ post_id: postId })
            if (res?.status === 'success' && res.analysis) {
                analysisData.value = res.analysis
                return true
            }
            if (!res || typeof res.status === 'undefined') {
                resultEndpointUnavailable = true
            }
        } catch (e: any) {
            if (!isAnalysisTransportError(e)) {
                throw e
            }
            resultEndpointUnavailable = true
        }

        if (resultEndpointUnavailable && fallbackRequestCount < 2 && i % 3 === 2) {
            fallbackRequestCount += 1
            currentLoadingText.value = '正在重新查询分析结果...'
            try {
                const fallbackRes = await getCommunityPostAiAnalysis({ post_id: postId })
                syncAiRemain(fallbackRes)
                let packet = extractPostAnalysisPacket(fallbackRes)
                if (shouldRefreshPostAnalysisCache(packet)) {
                    currentLoadingText.value = '正在刷新图片分析结果...'
                    const forceRes = await getCommunityPostAiAnalysis({ post_id: postId, force: 1 })
                    syncAiRemain(forceRes)
                    packet = extractPostAnalysisPacket(forceRes)
                }
                if (packet.analysis) {
                    analysisData.value = packet.analysis
                    return true
                }
            } catch (e: any) {
                if (!isAnalysisTransportError(e)) {
                    throw e
                }
            }
        }
    }
    return false
}

const typeWriter = (text: string, target: typeof streamReasoning, speed = 30): Promise<void> => {
    return new Promise((resolve) => {
        if (!text) { target.value = ''; resolve(); return }
        target.value = ''
        let i = 0
        const tick = () => {
            if (i < text.length) {
                target.value += text[i]
                i++
                const t = setTimeout(tick, speed) as unknown as number
                typeTimers.push(t)
            } else {
                resolve()
            }
        }
        tick()
    })
}

const fetchMatchPredict = async (matchId: number) => {
    loading.value = true
    errorMsg.value = ''
    predictionData.value = null
    factorsData.value = null
    oddsData.value = null
    summaryData.value = null
    streamReasoning.value = ''
    streamOddsExplain.value = ''
    streamSummary.value = ''
    clearTypeTimers()
    startAnalysisTimer()

    const sections = [
        { key: 'prediction', ref: predictionData, loadingRef: predictionLoading },
        { key: 'factors', ref: factorsData, loadingRef: factorsLoading },
        { key: 'odds', ref: oddsData, loadingRef: oddsLoading },
        { key: 'summary', ref: summaryData, loadingRef: summaryLoading },
    ] as const

    for (const s of sections) {
        currentLoadingText.value = sectionLoadingText[s.key]
        s.loadingRef.value = true
        try {
            const res = await getMatchPredictSection({ match_id: matchId, section: s.key })
            s.ref.value = res.data || {}
            if (res.remain_count !== undefined) {
                freeRemain.value = res.remain_count
            }
            if (res.match_info && !matchInfo.value.home_team) {
                matchInfo.value = res.match_info
            }
            if (s.key === 'prediction') {
                loading.value = false
                typeWriter(res.data?.prediction?.reasoning || '', streamReasoning, 25)
            } else if (s.key === 'odds') {
                typeWriter(res.data?.odds_opinion?.explanation || '', streamOddsExplain, 25)
            } else if (s.key === 'summary') {
                typeWriter(res.data?.summary || '', streamSummary, 20)
            }
        } catch (e: any) {
            if (s.key === 'prediction') {
                errorMsg.value = getAnalysisErrorMessage(e)
                loading.value = false
                stopAnalysisTimer()
                return
            }
        } finally {
            s.loadingRef.value = false
        }
    }

    stopAnalysisTimer()
}

const fetchArticleAnalysis = async (articleId: number) => {
    loading.value = true
    errorMsg.value = ''
    analysisData.value = null
    startAnalysisTimer()
    try {
        const res = await getArticleAnalysis({ article_id: articleId })
        syncAiRemain(res)
        analysisData.value = res.analysis
    } catch (e: any) {
        errorMsg.value = getAnalysisErrorMessage(e)
    } finally {
        loading.value = false
        stopAnalysisTimer()
    }
}

const fetchPostMeta = async (postId: number) => {
    try {
        const res = await getCommunityPostDetail({ id: postId })
        const content = String(res?.content || '').trim()
        if (content) {
            const firstLine = content.split('\n')[0].trim()
            postTitle.value = firstLine.slice(0, 30) || postTitle.value
        }
        postTags.value = Array.isArray(res?.tags) ? res.tags : []
        postAuthor.value = String(res?.user?.nickname || '')
        postImages.value = Array.isArray(res?.images)
            ? res.images.map((item: any) => String(item || '')).filter(Boolean)
            : []
    } catch (_e) {
        // 帖子元信息获取失败不影响AI分析主流程
    }
}

const fetchPostAnalysis = async (postId: number) => {
    loading.value = true
    errorMsg.value = ''
    analysisData.value = null
    startAnalysisTimer()
    try {
        const res = await getCommunityPostAiAnalysis({ post_id: postId })
        syncAiRemain(res)
        let packet = extractPostAnalysisPacket(res)
        if (shouldRefreshPostAnalysisCache(packet)) {
            currentLoadingText.value = '正在刷新图片分析结果...'
            const forceRes = await getCommunityPostAiAnalysis({ post_id: postId, force: 1 })
            syncAiRemain(forceRes)
            packet = extractPostAnalysisPacket(forceRes)
        }
        if (!packet.analysis) {
            throw { message: 'AI分析结果为空，请稍后重试', statusCode: 502 }
        }
        analysisData.value = packet.analysis
    } catch (e: any) {
        if (isAnalysisTransportError(e)) {
            currentLoadingText.value = '请求连接已断开，正在查询服务器分析结果...'
            try {
                const resolved = await waitForPostAnalysisResult(postId)
                if (!resolved) {
                    errorMsg.value = getAnalysisErrorMessage(e)
                }
            } catch (pollError: any) {
                errorMsg.value = getAnalysisErrorMessage(pollError)
            }
        } else {
            errorMsg.value = getAnalysisErrorMessage(e)
        }
    } finally {
        loading.value = false
        stopAnalysisTimer()
    }
}

const retryAnalysis = () => {
    if (analysisType.value === 'match') {
        fetchMatchPredict(refId)
    } else if (analysisType.value === 'article') {
        fetchArticleAnalysis(refId)
    } else if (analysisType.value === 'post') {
        fetchPostAnalysis(refId)
    }
}

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

const riskText = (level: string) => {
    const map: Record<string, string> = { low: '低', medium: '中', high: '高' }
    return map[level] || level || '-'
}

const domainText = (domain: string) => {
    const map: Record<string, string> = {
        article: '资讯',
        post: '帖子',
        lottery: '彩票',
        match: '赛事'
    }
    return map[domain] || '知识库'
}

onLoad((options: any) => {
    analysisType.value = options.type || 'match'
    refId = Number(options.id || 0)
    articleTitle.value = decodeURIComponent(options.title || '')
    postTitle.value = decodeURIComponent(options.title || '')

    if (!userStore.isLogin) {
        loading.value = false
        uni.showModal({
            title: '提示',
            content: '需要登录才能使用AI分析',
            confirmText: '去登录',
            cancelText: '返回',
            success: (res) => {
                if (res.confirm) {
                    uni.navigateTo({ url: '/pages/login/login' })
                } else {
                    uni.navigateBack()
                }
            }
        })
        return
    }

    if (analysisType.value === 'match' && refId > 0) {
        fetchMatchPredict(refId)
    } else if (analysisType.value === 'article' && refId > 0) {
        fetchArticleAnalysis(refId)
    } else if (analysisType.value === 'post' && refId > 0) {
        fetchPostMeta(refId)
        fetchPostAnalysis(refId)
    } else {
        loading.value = false
        errorMsg.value = '参数错误'
    }
})

onUnmounted(() => {
    isPageAlive = false
    clearTypeTimers()
    stopAnalysisTimer()
})
</script>

<style lang="scss" scoped>
.ai-page {
    min-height: 100vh;
    background: linear-gradient(180deg, #1a1a2e 0%, #16213e 30%, #f5f5f5 30%);
}

.ai-nav {
    background: transparent;

    &__inner {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
        height: 88rpx;
        padding: 0 24rpx;
    }

    &__back {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    &__title {
        font-size: 34rpx;
        font-weight: 600;
        color: #fff;
    }

    &__placeholder {
        width: 60rpx;
    }
}

.ai-scroll {
    background: transparent;
}

.ai-match-card {
    margin: 0 32rpx 24rpx;
    padding: 32rpx;
    background: rgba(255, 255, 255, 0.15);
    border-radius: 16rpx;
    backdrop-filter: blur(10px);

    &__teams {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        gap: 24rpx;
    }

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

    &__vs {
        font-size: 24rpx;
        color: #185dff;
        font-weight: 700;
        background: rgba(229, 77, 66, 0.2);
        padding: 4rpx 16rpx;
        border-radius: 8rpx;
    }

    &__meta {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        gap: 20rpx;
        margin-top: 16rpx;
        font-size: 22rpx;
        color: rgba(255, 255, 255, 0.7);
    }
}

.ai-article-card {
    margin: 0 32rpx 24rpx;
    padding: 24rpx 32rpx;
    background: rgba(255, 255, 255, 0.15);
    border-radius: 16rpx;

    &--post {
        backdrop-filter: blur(10px);
    }

    &__eyebrow {
        display: block;
        margin-bottom: 10rpx;
        font-size: 20rpx;
        font-weight: 700;
        color: rgba(255, 255, 255, 0.72);
        letter-spacing: 2rpx;
    }

    &__title {
        font-size: 28rpx;
        color: #fff;
        font-weight: 500;
        line-height: 1.5;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }

    &__desc {
        display: block;
        margin-top: 14rpx;
        font-size: 22rpx;
        color: rgba(255, 255, 255, 0.78);
        line-height: 1.6;
    }
}

.ai-post-images {
    margin: -8rpx 32rpx 24rpx;
    padding: 24rpx;
    background: rgba(255, 255, 255, 0.92);
    border-radius: 20rpx;
    box-shadow: 0 12rpx 36rpx rgba(22, 33, 62, 0.12);

    &__head {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 18rpx;
    }

    &__title {
        font-size: 26rpx;
        font-weight: 700;
        color: #16213e;
    }

    &__count {
        font-size: 22rpx;
        color: #6b7280;
    }

    &__item {
        display: block;
        width: 100%;
        border-radius: 16rpx;
        overflow: hidden;
        background: #f3f4f6;

        & + & {
            margin-top: 18rpx;
        }
    }
}

.ai-vip-bar {
    padding: 0 32rpx;
    margin-bottom: 24rpx;

    &__inner {
        display: flex;
        align-items: center;
        gap: 12rpx;
        padding: 16rpx 24rpx;
        border-radius: 12rpx;

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

        &--free {
            background: rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(10px);
        }
    }

    &__badge {
        font-size: 20rpx;
        font-weight: 900;
        color: #fff;
        background: linear-gradient(135deg, #f59e0b, #d97706);
        padding: 4rpx 14rpx;
        border-radius: 8rpx;
        letter-spacing: 2rpx;

        &--free {
            background: linear-gradient(135deg, #6366f1, #8b5cf6);
        }
    }

    &__text {
        font-size: 22rpx;
        color: #000000;
        flex: 1;
    }
}

.ai-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 120rpx 0;

    &__dots {
        display: flex;
        flex-direction: row;
        gap: 16rpx;
        margin-bottom: 32rpx;
    }

    &__dot {
        width: 16rpx;
        height: 16rpx;
        border-radius: 50%;
        background: #185dff;
        animation: pulse 1.2s ease-in-out infinite;

        &:nth-child(2) {
            animation-delay: 0.2s;
        }

        &:nth-child(3) {
            animation-delay: 0.4s;
        }
    }

    &__text {
        font-size: 30rpx;
        color: #333;
        font-weight: 500;
    }

    &__timer {
        margin-top: 14rpx;
        font-size: 24rpx;
        color: #185dff;
        font-weight: 600;
    }

    &__hint {
        font-size: 24rpx;
        color: #999;
        margin-top: 12rpx;
    }
}

@keyframes pulse {

    0%,
    80%,
    100% {
        transform: scale(0.6);
        opacity: 0.5;
    }

    40% {
        transform: scale(1);
        opacity: 1;
    }
}

.ai-result {
    padding: 0 24rpx;
}

.ai-section {
    background: #fff;
    border-radius: 16rpx;
    padding: 28rpx;
    margin-bottom: 20rpx;

    &--fadein {
        animation: sectionFadeIn 0.5s ease-out;
    }

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

    &__icon {
        font-size: 32rpx;
    }

    &__title {
        font-size: 30rpx;
        font-weight: 600;
        color: #333;
    }
}

@keyframes sectionFadeIn {
    from {
        opacity: 0;
        transform: translateY(20rpx);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.ai-section-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 32rpx 0;

    &__text {
        font-size: 24rpx;
        color: #999;
        margin-top: 16rpx;
    }

    &__time {
        margin-top: 10rpx;
        font-size: 22rpx;
        color: #185dff;
        font-weight: 600;
    }
}

.ai-predict {
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 24rpx;
    margin-bottom: 16rpx;

    &__main {
        flex: 1;
    }

    &__result {
        font-size: 40rpx;
        font-weight: 700;
        color: #185dff;
        display: block;
        margin-bottom: 12rpx;
    }

    &__conf {
        display: flex;
        flex-direction: row;
        align-items: center;
        gap: 12rpx;
        font-size: 22rpx;
        color: #999;
    }

    &__bar {
        flex: 1;
        height: 12rpx;
        background: #f0f0f0;
        border-radius: 6rpx;
        overflow: hidden;
    }

    &__bar-fill {
        height: 100%;
        background: linear-gradient(90deg, #185dff, #ff8a65);
        border-radius: 6rpx;
        transition: width 0.8s ease;
    }

    &__pct {
        font-size: 24rpx;
        color: #185dff;
        font-weight: 600;
    }

    &__score {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 16rpx 24rpx;
        background: #f8f8f8;
        border-radius: 12rpx;
    }

    &__score-label {
        font-size: 20rpx;
        color: #999;
    }

    &__score-val {
        font-size: 36rpx;
        font-weight: 700;
        color: #333;
        margin-top: 4rpx;
    }

    &__reason {
        font-size: 26rpx;
        color: #666;
        line-height: 1.7;
        display: block;
    }
}

.ai-strength {
    &__row {
        display: flex;
        flex-direction: row;
        align-items: center;
        gap: 16rpx;
        margin-bottom: 16rpx;
        font-size: 24rpx;
        color: #666;

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

        text:first-child {
            width: 120rpx;
            text-align: right;
            flex-shrink: 0;
        }

        text:last-child {
            width: 60rpx;
            text-align: center;
            font-weight: 600;
            flex-shrink: 0;
        }
    }

    &__bar {
        flex: 1;
        height: 20rpx;
        background: #f0f0f0;
        border-radius: 10rpx;
        overflow: hidden;
    }

    &__fill {
        height: 100%;
        border-radius: 10rpx;
        transition: width 0.8s ease;

        &--home {
            background: linear-gradient(90deg, #185dff, #ff8a65);
        }

        &--away {
            background: linear-gradient(90deg, #3b82f6, #60a5fa);
        }
    }
}

.ai-tags {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    gap: 16rpx;
}

.ai-tag {
    padding: 8rpx 20rpx;
    border-radius: 20rpx;
    font-size: 24rpx;

    &--green {
        background: #e8f5e9;
        color: #2e7d32;
    }

    &--red {
        background: #fce4ec;
        color: #c62828;
    }

    &--blue {
        background: #e3f2fd;
        color: #1565c0;
    }

    &--gray {
        background: #f5f5f5;
        color: #666;
    }
}

.ai-odds {
    &__value {
        font-size: 28rpx;
        color: #185dff;
        font-weight: 600;
        display: block;
        margin-bottom: 8rpx;
    }

    &__explain {
        font-size: 26rpx;
        color: #666;
        line-height: 1.7;
    }
}

.ai-summary {
    font-size: 28rpx;
    color: #444;
    line-height: 1.8;
    word-break: break-word;
}

.ai-list {
    &__item {
        display: flex;
        flex-direction: row;
        gap: 16rpx;
        margin-bottom: 16rpx;

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

    &__num {
        width: 40rpx;
        height: 40rpx;
        border-radius: 50%;
        background: #185dff;
        color: #fff;
        font-size: 22rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
    }

    &__text {
        flex: 1;
        font-size: 26rpx;
        color: #444;
        line-height: 1.6;
    }
}

.ai-post-score {
    display: flex;
    align-items: center;
    gap: 20rpx;

    &__badge {
        width: 132rpx;
        height: 132rpx;
        border-radius: 28rpx;
        background: linear-gradient(135deg, #185dff, #5da8ff);
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
        box-shadow: 0 16rpx 34rpx rgba(24, 93, 255, 0.2);
    }

    &__value {
        font-size: 42rpx;
        line-height: 1;
        color: #fff;
        font-weight: 800;
    }

    &__label {
        margin-top: 10rpx;
        font-size: 20rpx;
        color: rgba(255, 255, 255, 0.9);
    }

    &__summary {
        flex: 1;
        font-size: 27rpx;
        color: #444;
        line-height: 1.75;
    }
}

.ai-post-inline {
    display: block;
    margin-top: 18rpx;
    font-size: 24rpx;
    color: #185dff;
    font-weight: 600;
}

.ai-post-history {
    flex: 1;

    &__title {
        display: block;
        font-size: 26rpx;
        color: #333;
        line-height: 1.6;
    }

    &__meta {
        display: block;
        margin-top: 8rpx;
        font-size: 22rpx;
        color: #999;
    }
}

.ai-evidence-card {
    padding: 22rpx 24rpx;
    margin-bottom: 16rpx;
    border-radius: 14rpx;
    background: #f8fbff;
    border: 1rpx solid #e5edff;

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

    &__meta {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 16rpx;
        margin-bottom: 10rpx;
        font-size: 21rpx;
    }

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

    &__source {
        color: #98a2b3;
    }

    &__title {
        display: block;
        font-size: 26rpx;
        color: #1f2937;
        font-weight: 600;
        line-height: 1.55;
    }

    &__content {
        display: block;
        margin-top: 10rpx;
        font-size: 23rpx;
        color: #667085;
        line-height: 1.7;
    }
}

.ai-sentiment {
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 20rpx;

    &__label {
        padding: 8rpx 24rpx;
        border-radius: 20rpx;
        font-size: 26rpx;
        font-weight: 500;

        &--positive {
            background: #e8f5e9;
            color: #2e7d32;
        }

        &--neutral {
            background: #fff3e0;
            color: #e65100;
        }

        &--negative {
            background: #fce4ec;
            color: #c62828;
        }
    }

    &__conf {
        font-size: 24rpx;
        color: #999;
    }
}

.ai-error {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 120rpx 0;

    &__icon {
        font-size: 80rpx;
        margin-bottom: 20rpx;
    }

    &__text {
        font-size: 28rpx;
        color: #999;
        margin-bottom: 32rpx;
    }

    &__btn {
        background: #185dff;
        color: #fff;
        font-size: 28rpx;
        padding: 16rpx 48rpx;
        border-radius: 32rpx;
    }
}

.ai-league-row {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    gap: 16rpx;
    margin-bottom: 16rpx;

    &__label {
        font-size: 24rpx;
        color: #999;
        width: 60rpx;
        flex-shrink: 0;
        padding-top: 8rpx;
    }
}

.ai-context {
    margin-top: 12rpx;
    padding: 16rpx;
    background: #f8f8f8;
    border-radius: 8rpx;
    font-size: 26rpx;
    color: #555;
    line-height: 1.6;
}

.ai-match-item {
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;

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

    &__teams {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        gap: 20rpx;
        margin-bottom: 10rpx;
    }

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

    &__vs {
        font-size: 22rpx;
        color: #185dff;
        font-weight: 700;
        background: rgba(229, 77, 66, 0.1);
        padding: 2rpx 12rpx;
        border-radius: 6rpx;
    }

    &__meta {
        display: flex;
        flex-direction: row;
        justify-content: center;
        gap: 20rpx;
        font-size: 22rpx;
        color: #999;
    }

    &__importance {
        display: block;
        margin-top: 8rpx;
        font-size: 22rpx;
        color: #f57f17;
        text-align: center;
    }
}

.ai-h2h-table {
    border: 1rpx solid #f0f0f0;
    border-radius: 8rpx;
    overflow: hidden;
    margin-bottom: 16rpx;

    &__head {
        display: flex;
        flex-direction: row;
        background: #f8f8f8;
        padding: 12rpx 0;
    }

    &__row {
        display: flex;
        flex-direction: row;
        padding: 14rpx 0;
        border-top: 1rpx solid #f0f0f0;

        &:nth-child(even) {
            background: #fafafa;
        }
    }

    &__cell {
        font-size: 22rpx;
        color: #666;
        text-align: center;
        flex: 1;

        &--date {
            flex: 1.4;
            color: #999;
        }

        &--team {
            flex: 1.3;
        }

        &--score {
            flex: 0.8;
        }

        &--score-val {
            color: #185dff;
            font-weight: 700;
        }
    }
}

.ai-h2h-summary {
    font-size: 24rpx;
    color: #888;
    line-height: 1.6;
    display: block;
}

.ai-betting {
    &__top {
        display: flex;
        flex-direction: row;
        align-items: flex-start;
        gap: 20rpx;
        margin-bottom: 20rpx;
    }

    &__predict {
        flex: 1;
    }

    &__result {
        font-size: 36rpx;
        font-weight: 700;
        color: #185dff;
        display: block;
        margin-bottom: 10rpx;
    }

    &__conf-row {
        display: flex;
        flex-direction: row;
        align-items: center;
        gap: 10rpx;
        font-size: 22rpx;
        color: #999;
    }

    &__conf-label {
        font-size: 22rpx;
        color: #999;
        flex-shrink: 0;
    }

    &__risk {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 16rpx 20rpx;
        border-radius: 12rpx;
        background: #f5f5f5;
        min-width: 90rpx;

        &--low {
            background: #e8f5e9;
        }

        &--medium {
            background: #fff3e0;
        }

        &--high {
            background: #fce4ec;
        }
    }

    &__risk-label {
        font-size: 20rpx;
        color: #999;
    }

    &__risk-val {
        font-size: 28rpx;
        font-weight: 700;
        color: #333;
        margin-top: 4rpx;
    }

    &__reason {
        font-size: 26rpx;
        color: #555;
        line-height: 1.7;
        display: block;
        margin-bottom: 16rpx;
    }

    &__factors {
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
        gap: 12rpx;
        margin-bottom: 16rpx;
    }

    &__value {
        display: flex;
        flex-direction: row;
        align-items: center;
        gap: 12rpx;
        padding: 14rpx 20rpx;
        background: #fff8e1;
        border-radius: 8rpx;
    }

    &__value-label {
        font-size: 24rpx;
        color: #f57f17;
        font-weight: 500;
    }

    &__value-text {
        font-size: 26rpx;
        color: #333;
        font-weight: 600;
    }
}

.ai-list {
    &__text {
        &--warn {
            color: #c62828;
        }
    }
}

.ai-cursor {
    color: #185dff;
    font-weight: 700;
    animation: blink 0.6s infinite;
}

@keyframes blink {

    0%,
    100% {
        opacity: 1;
    }

    50% {
        opacity: 0;
    }
}

.ai-disclaimer {
    margin: 20rpx 24rpx;
    padding: 20rpx;
    background: #fff8e1;
    border-radius: 8rpx;
    font-size: 22rpx;
    color: #f57f17;
    line-height: 1.6;
    text-align: center;
}
</style>
