{% extends "base.html" %}
{% load static %}
{% load dashboard_tags %}

{% block title %}AgomTradePro - 投资指挥中心{% endblock %}

{% block extra_css %}
<!-- ECharts -->
<script src="{% static 'vendor/js/echarts.min.js' %}"></script>
<link rel="stylesheet" href="{% static 'css/home.css' %}">
<!-- Teaching Module -->
<link rel="stylesheet" href="{% static 'css/teaching.css' %}">
<!-- Main Workflow Panel (WP-3) -->
<link rel="stylesheet" href="{% static 'css/main-workflow.css' %}">
<!-- Shared Chat Renderer -->
<link rel="stylesheet" href="{% static 'css/shared/shared-chat-renderer.css' %}">
{% endblock %}

{% block content %}
<!-- Hidden JSON data for JavaScript -->
{{ alpha_provider_status|json_script:"providerData" }}
{{ alpha_ic_trends|json_script:"icTrendsData" }}
{{ browser_notification_payload|json_script:"browserNotificationPayload" }}

<div class="home-layout">
    <!-- 左侧导航栏 -->
    <aside class="home-sidebar">
        <div class="sidebar-header">
            <h2 class="sidebar-title">功能导航</h2>
        </div>

        <nav class="sidebar-nav">
            <!-- 宏观环境 -->
            <div class="nav-section">
                <div class="nav-section-title">宏观环境</div>
                <a href="{% url 'regime:dashboard' %}" class="nav-item">
                    <span class="nav-icon">📈</span>
                    <span class="nav-text">Regime 判定</span>
                </a>
                <a href="{% url 'policy:workbench' %}" class="nav-item">
                    <span class="nav-icon">📰</span>
                    <span class="nav-text">政策/情绪/热点工作台</span>
                </a>
                {% if user.is_staff %}
                <a href="{% url 'policy:rss-manage' %}" class="nav-item">
                    <span class="nav-icon">🗞️</span>
                    <span class="nav-text">RSS 源管理</span>
                </a>
                {% endif %}
                <a href="{% url 'macro:data' %}" class="nav-item">
                    <span class="nav-icon">📊</span>
                    <span class="nav-text">宏观数据</span>
                </a>
            </div>

            <!-- 投资决策 -->
            <div class="nav-section">
                <div class="nav-section-title">投资决策</div>
                <a href="{% url 'decision-workspace' %}" class="nav-item">
                    <span class="nav-icon">🧭</span>
                    <span class="nav-text">决策工作台</span>
                </a>
                <a href="{% url 'signal:manage' %}" class="nav-item">
                    <span class="nav-icon">🎯</span>
                    <span class="nav-text">投资信号</span>
                </a>
                <a href="{% url 'dashboard:alpha_ranking' %}" class="nav-item">
                    <span class="nav-icon">⭐</span>
                    <span class="nav-text">Alpha 完整排名</span>
                </a>
                <a href="{% url 'backtest:create' %}" class="nav-item">
                    <span class="nav-icon">🧪</span>
                    <span class="nav-text">策略回测</span>
                </a>
                <a href="{% url 'filter:dashboard' %}" class="nav-item">
                    <span class="nav-icon">🔍</span>
                    <span class="nav-text">股票筛选</span>
                </a>
            </div>

            <!-- 资产管理 -->
            <div class="nav-section">
                <div class="nav-section-title">资产管理</div>
                <a href="{% url 'account:profile' %}#positions" class="nav-item">
                    <span class="nav-icon">💼</span>
                    <span class="nav-text">持仓管理</span>
                </a>
                <a href="{% url 'account:profile' %}#portfolio" class="nav-item">
                    <span class="nav-icon">📦</span>
                    <span class="nav-text">组合配置</span>
                </a>
                <a href="{% url 'share:manage' %}" class="nav-item">
                    <span class="nav-icon">🔗</span>
                    <span class="nav-text">账户分享</span>
                </a>
                <a href="{% url 'equity:screen' %}" class="nav-item">
                    <span class="nav-icon">📈</span>
                    <span class="nav-text">股票分析</span>
                </a>
                <a href="{% url 'fund:dashboard' %}" class="nav-item">
                    <span class="nav-icon">💰</span>
                    <span class="nav-text">基金分析</span>
                </a>
            </div>

            <!-- 系统设置 -->
            <div class="nav-section">
                <div class="nav-section-title">系统</div>
                <a href="{% url 'audit:review' %}" class="nav-item">
                    <span class="nav-icon">🔍</span>
                    <span class="nav-text">事后审计</span>
                </a>
                <a href="{% url 'settings-center' %}" class="nav-item">
                    <span class="nav-icon">⚙️</span>
                    <span class="nav-text">设置中心</span>
                </a>
                <a href="{% url 'settings-mcp-tools' %}" class="nav-item">
                    <span class="nav-icon">🧩</span>
                    <span class="nav-text">MCP 工具目录</span>
                </a>
                <a href="{% url 'account:mcp_guide' %}" class="nav-item">
                    <span class="nav-icon">🔌</span>
                    <span class="nav-text">MCP 接入说明</span>
                </a>
                <a href="{% url 'docs' %}" class="nav-item">
                    <span class="nav-icon">📘</span>
                    <span class="nav-text">系统文档</span>
                </a>
            </div>
        </nav>

        <!-- 快捷状态 -->
        <div class="sidebar-footer">
            <!-- 教学指南按钮 -->
            <button class="teaching-toggle-btn" onclick="openTeachingModal()">
                <span class="btn-icon">📚</span>
                <span class="btn-text">教学指南</span>
            </button>
            <div class="status-card">
                <div class="status-item">
                    <span class="status-label">当前 Regime</span>
                    <span class="status-value regime-{{ current_regime|default:"unknown"|lower }}">{{ current_regime|default:"Unknown" }}</span>
                </div>
                <div class="status-item">
                    <span class="status-label">政策档位</span>
                    <span class="status-value policy-{{ policy_level|default:"P0"|lower }}">{{ policy_level|default:"P0" }}</span>
                </div>
            </div>
        </div>
    </aside>

    <!-- 中间主内容区 -->
    <main class="home-main">
        <!-- 顶部欢迎区 -->
        <header class="home-header">
            <div class="header-welcome">
                <h1 class="home-title">欢迎回来，{{ display_name|default:user.username }}</h1>
                <p class="home-subtitle">AgomTradePro 战略资产配置框架 - 投资指挥中心</p>
            </div>
            <div class="header-actions">
                <a href="{% url 'decision-workspace' %}" class="refresh-btn" style="text-decoration: none;">
                    <span>🧭 发起新决策</span>
                </a>
                <button type="button" id="pulseNotifyToggle" class="refresh-btn">
                    <span>🔔 Pulse 通知</span>
                </button>
            </div>
        </header>

        {% include "components/regime_status_bar.html" %}

        <div class="priority-panels-grid">
            {% include "components/attention_items.html" %}
            {% include "components/action_recommendation.html" %}
        </div>

        <div style="margin-bottom: var(--gap);">
            {% include "components/pulse_card.html" %}
        </div>

        <div style="margin-bottom: var(--gap);">
            {% include "components/market_thermometer_card.html" %}
        </div>

        <section class="account-overview-section">
            <div class="section-header">
                <h2 class="section-title">我的账户</h2>
                <a href="{% url 'simulated_trading:my-accounts' %}" class="section-link">全部账户 →</a>
            </div>
            {% if investment_accounts %}
            <div class="account-tag-grid">
                {% for account in investment_accounts %}
                <a href="{% url 'simulated_trading:my-account-detail' account.id %}"
                   class="account-tag-card account-tag-card-{{ account.type_code }}">
                    <div class="account-tag-topline">
                        <span class="account-type-badge">{{ account.type_label }}</span>
                        <span class="account-status {% if account.is_active %}is-active{% else %}is-inactive{% endif %}">
                            {% if account.is_active %}活跃{% else %}停用{% endif %}
                        </span>
                    </div>
                    <div class="account-tag-name">{{ account.name }}</div>
                    <div class="account-tag-assets">¥{{ account.total_value|floatformat:2 }}</div>
                    <div class="account-tag-meta">
                        <span>现金 ¥{{ account.cash|floatformat:0 }}</span>
                        <span>持仓 ¥{{ account.market_value|floatformat:0 }}</span>
                    </div>
                    <div class="account-tag-return {% if account.total_return >= 0 %}positive{% else %}negative{% endif %}">
                        收益率 {{ account.total_return|floatformat:2 }}%
                    </div>
                </a>
                {% endfor %}
            </div>
            {% else %}
            <div class="empty-state">
                <div class="empty-icon">📂</div>
                <p>暂无投资账户</p>
            </div>
            {% endif %}
        </section>

        <!-- 主流程面板：上移到首屏顶部 -->
        {% include "dashboard/main_workflow_panel.html" %}

        <!-- 核心指标卡片 -->
        <section class="metrics-grid">
            <div class="metric-card">
                <div class="metric-header">
                    <span class="metric-icon">📊</span>
                    <span class="metric-title">PMI (增长)</span>
                </div>
                <div class="metric-value {% if pmi_value and pmi_value >= 50 %}positive{% else %}negative{% endif %}">
                    {{ pmi_value|default:"-"|floatformat:1 }}
                </div>
                <div class="metric-footer">
                    <span class="metric-label">{% if pmi_value and pmi_value >= 50 %}扩张{% elif pmi_value %}收缩{% else %}-{% endif %}</span>
                </div>
            </div>

            <div class="metric-card">
                <div class="metric-header">
                    <span class="metric-icon">📈</span>
                    <span class="metric-title">CPI (通胀)</span>
                </div>
                <div class="metric-value {% if cpi_value and cpi_value > 2 %}positive{% else %}negative{% endif %}">
                    {{ cpi_value|default:"-"|floatformat:1 }}%
                </div>
                <div class="metric-footer">
                    <span class="metric-label">{% if cpi_value > 2 %}高通胀{% elif cpi_value >= 1 %}温和通胀{% elif cpi_value >= 0 %}低通胀{% elif cpi_value is not none %}通缩{% else %}-{% endif %}</span>
                </div>
            </div>

            <div class="metric-card">
                <div class="metric-header">
                    <span class="metric-icon">🎯</span>
                    <span class="metric-title">置信度</span>
                </div>
                <div class="metric-value">
                    {{ regime_confidence_pct|default:0|floatformat:0 }}%
                </div>
                <div class="metric-footer">
                    <span class="metric-label">{{ regime_date|default:"-" }}</span>
                </div>
            </div>

            <div class="metric-card">
                <div class="metric-header">
                    <span class="metric-icon">💼</span>
                    <span class="metric-title">持仓数量</span>
                </div>
                <div class="metric-value">
                    {{ position_count|default:0 }}
                </div>
                <div class="metric-footer">
                    <span class="metric-label">仓位: {{ invested_ratio|floatformat:1 }}%</span>
                </div>
            </div>
        </section>

        {% if regime_warnings %}
        <section class="section-card" style="margin-bottom: 16px; border-left: 4px solid #f59e0b;">
            <div style="padding: 12px 16px;">
                <strong>Regime 数据告警（{{ regime_data_health }}）</strong>
                <ul style="margin: 8px 0 0 18px;">
                    {% for warning in regime_warnings %}
                    <li>{{ warning }}</li>
                    {% endfor %}
                </ul>
            </div>
        </section>
        {% endif %}

        <!-- 决策模式状态卡片 -->
        <section class="decision-plane-section">
            <div class="section-header">
                <h2 class="section-title">🎯 决策模式状态</h2>
                <a href="{% url 'decision-workspace' %}" class="section-link">进入决策模式 →</a>
            </div>
            <div class="decision-plane-grid">
                <!-- Beta Gate 状态 -->
                <div class="decision-card beta-gate">
                    <div class="decision-card-header">
                        <span class="decision-icon">🚪</span>
                        <span class="decision-title">Beta 闸门</span>
                        <a href="{% url 'decision-workspace' %}" class="decision-link">进入步骤 →</a>
                    </div>
                    <div class="decision-card-body">
                        <div class="decision-status">
                            <span class="status-label">可见资产类别</span>
                            <span class="status-value">{{ beta_gate_visible_classes|default:"-" }}</span>
                        </div>
                    </div>
                </div>

                <!-- Alpha 面板 -->
                <div class="decision-card alpha-panel">
                    <div class="decision-card-header">
                        <span class="decision-icon">⚡</span>
                        <span class="decision-title">Alpha 面板</span>
                        <a href="{% url 'decision-workspace' %}" class="decision-link">进入步骤 →</a>
                    </div>
                    <div class="decision-card-body">
                        <div class="decision-stats">
                            <div class="decision-stat">
                                <span class="stat-value">{{ alpha_watch_count|default:0 }}</span>
                                <span class="stat-label">观察</span>
                            </div>
                            <div class="decision-stat">
                                <span class="stat-value">{{ alpha_candidate_count|default:0 }}</span>
                                <span class="stat-label">候选</span>
                            </div>
                            <div class="decision-stat">
                                <span class="stat-value">{{ alpha_actionable_count|default:0 }}</span>
                                <span class="stat-label">可行动</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 决策配额 -->
                <div class="decision-card quota">
                    <div class="decision-card-header">
                        <span class="decision-icon">⏱️</span>
                        <span class="decision-title">决策配额</span>
                        <a href="{% url 'decision-workspace' %}" class="decision-link">进入步骤 →</a>
                    </div>
                    <div class="decision-card-body">
                        <div class="decision-status">
                            <span class="status-label">本期配额</span>
                            <span class="status-value">{{ quota_total|default:0 }}</span>
                        </div>
                        <div class="decision-status">
                            <span class="status-label">已占用</span>
                            <span class="status-value">{{ quota_used|default:0 }}</span>
                        </div>
                        <div class="decision-status">
                            <span class="status-label">剩余额度</span>
                            <span class="status-value">{{ quota_remaining|default:0 }}</span>
                        </div>
                        <div class="quota-progress">
                            <div class="quota-progress-bar" style="width: {{ quota_usage_percent|default:0 }}%"></div>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- Alpha 入口：完整排名与参数切换移至专门页面 -->
        <section class="alpha-visualization-section alpha-summary-section">
            <div class="section-header">
                <div>
                    <h2 class="section-title">🤖 Alpha 排名</h2>
                    <p class="section-subtitle">
                        首页不再加载 Alpha 排行数据；完整排名、scope、组合、股票池模式和返回条数在专门页调整。
                    </p>
                </div>
                <div class="header-actions alpha-summary-actions">
                    <a href="{% url 'dashboard:alpha_ranking' %}?alpha_scope={{ selected_alpha_scope|default:'portfolio' }}{% if selected_portfolio_id and selected_alpha_scope != 'general' %}&portfolio_id={{ selected_portfolio_id }}{% endif %}{% if selected_alpha_pool_mode and selected_alpha_scope != 'general' %}&pool_mode={{ selected_alpha_pool_mode|urlencode }}{% endif %}&top_n=200" class="refresh-btn">
                        <span>查看完整排名与参数</span>
                    </a>
                    <a href="{% url 'dashboard:alpha_history' %}{% if selected_portfolio_id %}?portfolio_id={{ selected_portfolio_id }}{% endif %}" class="refresh-btn">
                        <span>推荐历史</span>
                    </a>
                    <a href="{% url 'equity:screen' %}?source=dashboard-alpha{% if selected_portfolio_id %}&portfolio_id={{ selected_portfolio_id }}{% endif %}{% if alpha_pool.pool_mode %}&pool_mode={{ alpha_pool.pool_mode }}{% endif %}" class="refresh-btn">
                        <span>进入个股筛选</span>
                    </a>
                </div>
            </div>

            <div class="alpha-metrics-grid">
                <div class="alpha-metric-card">
                    <div class="metric-icon">🏷️</div>
                    <div class="metric-content">
                        <div class="metric-title">当前口径</div>
                        <div class="metric-value">{% if selected_alpha_scope == 'general' %}通用{% else %}账户{% endif %}</div>
                        <div class="metric-subtitle">进入完整排名页后加载</div>
                    </div>
                </div>
                <div class="alpha-metric-card">
                    <div class="metric-icon">📊</div>
                    <div class="metric-content">
                        <div class="metric-title">首页加载</div>
                        <div class="metric-value">已关闭</div>
                        <div class="metric-subtitle">排行数据不阻塞首屏</div>
                    </div>
                </div>
                <div class="alpha-metric-card">
                    <div class="metric-icon">✅</div>
                    <div class="metric-content">
                        <div class="metric-title">完整排名</div>
                        <div class="metric-value">入口</div>
                        <div class="metric-subtitle">集中查看 Alpha 结果</div>
                    </div>
                </div>
                <div class="alpha-metric-card">
                    <div class="metric-icon">🛡️</div>
                    <div class="metric-content">
                        <div class="metric-title">推荐历史</div>
                        <div class="metric-value">入口</div>
                        <div class="metric-subtitle">查看历史快照</div>
                    </div>
                </div>
            </div>

            <div class="alpha-summary-grid">
                <div class="alpha-summary-card">
                    <div class="card-header">
                        <h3>完整 Alpha 排名</h3>
                        <span class="card-badge">专门页面</span>
                    </div>
                    <p class="alpha-summary-empty">Alpha 排行已从首页移除，避免账户级股票池、评分缓存和退出链路阻塞首页打开。</p>
                    <div class="alpha-summary-footer">
                        <a href="{% url 'dashboard:alpha_ranking' %}?alpha_scope={{ selected_alpha_scope|default:'portfolio' }}{% if selected_portfolio_id and selected_alpha_scope != 'general' %}&portfolio_id={{ selected_portfolio_id }}{% endif %}{% if selected_alpha_pool_mode and selected_alpha_scope != 'general' %}&pool_mode={{ selected_alpha_pool_mode|urlencode }}{% endif %}&top_n=200" class="alpha-section-link">打开完整排名</a>
                    </div>
                </div>

                <div class="alpha-summary-card">
                    <div class="card-header">
                        <h3>相关入口</h3>
                        <span class="card-badge">快速操作</span>
                    </div>
                    <div class="alpha-summary-meta">
                        <span>股票池模式 {{ selected_alpha_pool_mode|default:"默认" }}</span>
                        <span>推荐历史 在历史页查看</span>
                        <span>个股筛选 在筛选页使用 Alpha 来源</span>
                    </div>
                    <div class="alpha-summary-footer">
                        <span>需要排行明细时直接进入完整排名页，首页只保留入口和决策概览。</span>
                    </div>
                </div>
            </div>
        </section>

        <!-- Regime 象限图 -->
        <section class="regime-section">
            <div class="section-header">
                <h2 class="section-title">Regime 象限</h2>
                <a href="{% url 'regime:dashboard' %}" class="section-link">查看详情 →</a>
            </div>
            <div class="regime-matrix">
                <div class="regime-axis-y">增长 ↑</div>
                <div class="regime-grid">
                    <div class="regime-quad {% if current_regime == 'Recovery' %}active{% endif %} quad-recovery">
                        <div class="quad-name">复苏</div>
                        <div class="quad-prob">{{ regime_distribution.Recovery|default:"0.00"|floatformat:2 }}</div>
                        <div class="quad-hint">高增低胀</div>
                    </div>
                    <div class="regime-quad {% if current_regime == 'Overheat' %}active{% endif %} quad-overheat">
                        <div class="quad-name">过热</div>
                        <div class="quad-prob">{{ regime_distribution.Overheat|default:"0.00"|floatformat:2 }}</div>
                        <div class="quad-hint">双高</div>
                    </div>
                    <div class="regime-quad {% if current_regime == 'Deflation' %}active{% endif %} quad-deflation">
                        <div class="quad-name">通缩</div>
                        <div class="quad-prob">{{ regime_distribution.Deflation|default:"0.00"|floatformat:2 }}</div>
                        <div class="quad-hint">双低</div>
                    </div>
                    <div class="regime-quad {% if current_regime == 'Stagflation' %}active{% endif %} quad-stagflation">
                        <div class="quad-name">滞胀</div>
                        <div class="quad-prob">{{ regime_distribution.Stagflation|default:"0.00"|floatformat:2 }}</div>
                        <div class="quad-hint">低增高胀</div>
                    </div>
                </div>
            </div>
        </section>

        <!-- 资产配置建议（新增） -->
        {% if allocation_advice %}
        <section class="allocation-advice-section">
            <div class="section-header">
                <h2 class="section-title">🎯 资产配置建议</h2>
                <span class="advice-badge">{{ allocation_advice.risk_profile_display }}</span>
            </div>
            <!-- 投资免责声明 -->
            {% include 'components/investment_disclaimer.html' %}
            <div class="allocation-advice-content">
                <!-- 配置对比 -->
                <div class="allocation-compare">
                    <div class="allocation-col current">
                        <h3>当前配置</h3>
                        <div class="allocation-bars">
                            {% for asset_class, value in allocation_advice.current_allocation.items %}
                            <div class="allocation-bar-item">
                                <span class="bar-label">{% if asset_class == 'equity' %}权益{% elif asset_class == 'fixed_income' %}债券{% elif asset_class == 'commodity' %}商品{% elif asset_class == 'cash' %}现金{% else %}{{ asset_class }}{% endif %}</span>
                                <div class="bar-track">
                                    <div class="bar-fill bar-current" style="width: {{ value|floatformat:0 }}%"></div>
                                </div>
                                <span class="bar-value">{{ value|floatformat:1 }}%</span>
                            </div>
                            {% endfor %}
                        </div>
                    </div>
                    <div class="allocation-arrow">→</div>
                    <div class="allocation-col target">
                        <h3>目标配置</h3>
                        <div class="allocation-bars">
                            {% for asset_class, value in allocation_advice.target_allocation.items %}
                            <div class="allocation-bar-item">
                                <span class="bar-label">{% if asset_class == 'equity' %}权益{% elif asset_class == 'fixed_income' %}债券{% elif asset_class == 'commodity' %}商品{% elif asset_class == 'cash' %}现金{% else %}{{ asset_class }}{% endif %}</span>
                                <div class="bar-track">
                                    <div class="bar-fill bar-target" style="width: {{ value }}%"></div>
                                </div>
                                <span class="bar-value">{{ value }}%</span>
                            </div>
                            {% endfor %}
                        </div>
                    </div>
                </div>

                <!-- 配置摘要 -->
                <div class="allocation-summary">
                    <p>{{ allocation_advice.summary }}</p>
                    {% if allocation_advice.expected_return %}
                    <div class="expected-metrics">
                        <span>预期年化: <strong>{{ allocation_advice.expected_return|floatformat:1 }}%</strong></span>
                        <span>预期波动: <strong>{{ allocation_advice.expected_volatility|floatformat:1 }}%</strong></span>
                        <span>夏普比率: <strong>{{ allocation_advice.sharpe_ratio|floatformat:2 }}</strong></span>
                    </div>
                    {% endif %}
                </div>

                <!-- 具体操作 -->
                {% if allocation_advice.trade_actions %}
                <div class="trade-actions">
                    <h4>具体操作建议</h4>
                    <div class="action-list">
                        {% for action in allocation_advice.trade_actions %}
                        <div class="action-item action-{{ action.action }}">
                            <span class="action-badge badge-{{ action.action }}">
                                {{ action.action|upper }}
                            </span>
                            <div class="action-details">
                                <div class="action-main">
                                    <strong>{{ action.asset_code }}</strong> {{ action.asset_name }}
                                    <span class="action-amount">¥{{ action.amount|floatformat:0 }}</span>
                                </div>
                                <div class="action-reason">{{ action.reason }}</div>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                </div>
                {% endif %}
            </div>
        </section>
        {% endif %}

        <!-- 持仓和信号 -->
        <div class="content-row">
            <!-- 持仓列表 -->
            <section class="content-card half">
                <div class="section-header">
                    <h2 class="section-title">当前持仓</h2>
                    <div class="header-actions">
                        <select id="positionAccountFilter" name="account_id" class="sort-select"
                                hx-get="/api/dashboard/positions/"
                                hx-trigger="change" hx-target="#positionList" hx-swap="innerHTML"
                                hx-include="#positionSort">
                            <option value="">全部账户</option>
                            {% for account in investment_accounts %}
                            <option value="{{ account.id }}">{{ account.name }}</option>
                            {% endfor %}
                        </select>
                        <select id="positionSort" name="sort" class="sort-select"
                                hx-get="/api/dashboard/positions/"
                                hx-trigger="change" hx-target="#positionList" hx-swap="innerHTML"
                                hx-include="#positionAccountFilter">
                            <option value="market_value">按市值</option>
                            <option value="pnl_pct">按收益率</option>
                            <option value="code">按代码</option>
                        </select>
                        <a href="{% url 'account:profile' %}#positions" class="section-link">管理 →</a>
                    </div>
                </div>
                <div class="card-body" id="positionList">
                    {% include 'dashboard/partials/positions_table.html' with positions=positions show_account=True %}
                </div>
            </section>

            <!-- 活跃信号 -->
            <section class="content-card half">
                <div class="section-header">
                    <h2 class="section-title">活跃信号</h2>
                    <a href="{% url 'signal:manage' %}" class="section-link">全部 →</a>
                </div>
                <div class="card-body">
                    {% if active_signals %}
                    <div class="signal-list">
                        {% for signal in active_signals|slice:":5" %}
                        <div class="signal-item">
                            <div class="signal-header">
                                <span class="signal-asset">{{ signal.asset_code }}</span>
                                <span class="signal-name">{{ signal.asset_name }}</span>
                                <span class="signal-badge badge-{{ signal.direction|lower }}">{{ signal.direction }}</span>
                            </div>
                            <p class="signal-logic">{{ signal.logic_desc|truncatewords:12 }}</p>
                        </div>
                        {% endfor %}
                    </div>
                    {% else %}
                    <div class="empty-state">
                        <div class="empty-icon">📊</div>
                        <p>暂无活跃信号</p>
                    </div>
                    {% endif %}
                </div>
            </section>
        </div>

        <!-- 资产配置图表 -->
        <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">
            <span style="font-size:13px;color:#666;">图表账户:</span>
            <select id="chartAccountFilter" class="sort-select">
                <option value="">全部账户</option>
                {% for account in investment_accounts %}
                <option value="{{ account.id }}">{{ account.name }}</option>
                {% endfor %}
            </select>
        </div>
        <div class="content-row">
            <section class="content-card half">
                <div class="section-header">
                    <h2 class="section-title">资产配置</h2>
                    <span class="chart-account-label" id="allocationAccountLabel">全部账户</span>
                </div>
                <div class="card-body" id="allocationChartWrap">
                    <div id="allocationChart" style="width:100%;height:300px;"></div>
                    <p class="text-muted" id="allocationEmpty" style="display:none;text-align:center;padding:40px 0;">暂无资产配置数据</p>
                </div>
            </section>

            <section class="content-card half">
                <div class="section-header">
                    <h2 class="section-title">收益趋势</h2>
                    <span class="chart-account-label" id="performanceAccountLabel">全部账户</span>
                </div>
                <div class="card-body" id="performanceChartWrap">
                    <div id="performanceChart" style="width:100%;height:300px;"></div>
                    <p class="text-muted" id="performanceEmpty" style="display:none;text-align:center;padding:40px 0;">暂无收益数据</p>
                </div>
            </section>
        </div>

        <!-- 持仓详情模态框 -->
        <div id="positionDetailModal" class="modal">
            <div class="modal-backdrop" onclick="closeModal('positionDetailModal')"></div>
            <div class="modal-dialog modal-lg">
                <div class="modal-header">
                    <h3 class="modal-title">持仓详情</h3>
                    <button class="modal-close" onclick="closeModal('positionDetailModal')">&times;</button>
                </div>
                <div class="modal-body" id="positionDetailContent">
                    <div class="app-loading-state app-loading-state--compact"><div class="app-spinner app-spinner--sm" aria-hidden="true"></div></div>
                </div>
            </div>
        </div>

        <!-- 系统状态 -->
        <section class="system-status">
            <div class="section-header">
                <h2 class="section-title">系统状态</h2>
            </div>
            <div class="status-grid">
                <div class="status-item-card">
                    <div class="status-icon">📊</div>
                    <div class="status-content">
                        <div class="status-name">宏观数据</div>
                        <div class="status-desc">
                            {% if regime_data_health %}
                                数据采集正常
                            {% else %}
                                数据不足或待刷新
                            {% endif %}
                        </div>
                    </div>
                    <div class="status-indicator {% if regime_data_health %}status-ok{% else %}status-warning{% endif %}"></div>
                </div>
                <div class="status-item-card">
                    <div class="status-icon">🎯</div>
                    <div class="status-content">
                        <div class="status-name">Regime 引擎</div>
                        <div class="status-desc">
                            {% if current_regime and regime_data_health %}
                                {{ current_regime }} 已更新
                            {% elif current_regime %}
                                {{ current_regime }}，数据待确认
                            {% else %}
                                等待有效宏观数据
                            {% endif %}
                        </div>
                    </div>
                    <div class="status-indicator {% if current_regime and regime_data_health %}status-ok{% else %}status-warning{% endif %}"></div>
                </div>
                <div class="status-item-card">
                    <div class="status-icon">📰</div>
                    <div class="status-content">
                        <div class="status-name">政策/情绪/热点</div>
                        <div class="status-desc">
                            {% if current_policy_level %}
                                政策档位 {{ current_policy_level }}
                            {% elif active_signals %}
                                {{ active_signals|length }} 条信号待复核
                            {% else %}
                                暂无最新事件
                            {% endif %}
                        </div>
                    </div>
                    <div class="status-indicator {% if current_policy_level or active_signals %}status-ok{% else %}status-warning{% endif %}"></div>
                </div>
                <div class="status-item-card">
                    <div class="status-icon">🤖</div>
                    <div class="status-content">
                        <div class="status-name">AI 助手</div>
                        <div class="status-desc">
                            {% if ai_insights %}
                                本地规则已生成
                            {% else %}
                                未生成建议
                            {% endif %}
                        </div>
                    </div>
                    <div class="status-indicator {% if ai_insights %}status-ok{% else %}status-warning{% endif %}"></div>
                </div>
                <div class="status-item-card status-qlib-card">
                    <div class="status-icon">🧠</div>
                    <div class="status-content">
                        <div class="status-name">Qlib AI <span class="qlib-badge">可选</span></div>
                        <div class="status-desc" id="qlibStatusDesc">检测中...</div>
                    </div>
                    <div class="status-indicator" id="qlibStatusIndicator"></div>
                </div>
            </div>
        </section>
    </main>

    <!-- 右侧 AI 聊天窗口 -->
    <aside class="home-chat">
        <div class="chat-header">
            <h2 class="chat-title">AI 助手</h2>
            <div class="chat-status"></div>
        </div>

        <div class="chat-messages" id="chatMessages">
            <div class="message message-system">
                <div class="message-content">
                    <p>你好！我是 AgomTradePro AI 助手。</p>
                    <p>我可以帮你：</p>
                    <ul>
                        <li>分析当前宏观环境</li>
                        <li>评估投资组合配置</li>
                        <li>回答投资相关问题</li>
                    </ul>
                </div>
            </div>
        </div>

        <div class="chat-input-area">
            <textarea id="chatInput" class="chat-input" placeholder="输入您的问题..." rows="3"></textarea>
            <button id="chatSendBtn" class="btn-send">
                <span>发送</span>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/>
                </svg>
            </button>
        </div>

        <!-- AI 建议卡片 -->
        <div class="ai-suggestions">
            <div class="suggestions-title">💡 快捷提问</div>
            <div class="suggestion-buttons">
                <button class="suggestion-btn" data-query="当前宏观环境如何？">当前宏观环境如何？</button>
                <button class="suggestion-btn" data-query="我的持仓配置合理吗？">我的持仓配置合理吗？</button>
                <button class="suggestion-btn" data-query="推荐什么投资策略？">推荐什么投资策略？</button>
            </div>
        </div>
    </aside>
</div>

<script src="{% static 'js/marked.min.js' %}"></script>
<script src="{% static 'js/mermaid.min.js' %}"></script>
<script src="{% static 'js/shared/shared-chat-renderer.js' %}"></script>
<script>
// API 配置
const API_URLS = {
    webChat: "/api/chat/web/",
    promptChatProviders: "/api/prompt/chat/providers",
    promptChatModels: "/api/prompt/chat/models",
    aiProviderManage: "{% url 'ai_provider:manage' %}",
    alphaStocks: "{% url 'api_dashboard:alpha_stocks' %}",
    alphaRefresh: "{% url 'api_dashboard:alpha_refresh' %}",
    decisionRequestCancelBase: "/api/decision-rhythm/requests/"
};
const DASHBOARD_ALPHA_DEFAULTS = {
    alphaScope: "{{ selected_alpha_scope|default:'portfolio'|escapejs }}",
    portfolioId: "{{ selected_portfolio_id|default:''|escapejs }}",
    poolMode: "{{ selected_alpha_pool_mode|default:alpha_pool.pool_mode|default:''|escapejs }}"
};

// 初始化共享渲染器
const chatRenderer = new AgomSharedChatRenderer({
    cssPrefix: 'agom-chat',
    enableMermaid: true,
    enableAnswerChain: true,
    enableSuggestionCard: true,
    onSuggestionExecute: async (action, card) => {
        await executeSuggestedAction(action);
    },
    onSuggestionCancel: (action, card) => {
        card.remove();
    }
});

// 聊天功能
const chatMessages = document.getElementById('chatMessages');
const chatInput = document.getElementById('chatInput');
const chatSendBtn = document.getElementById('chatSendBtn');
let chatSessionId = null;
let chatHistory = [];

function addMessage(content, isSystem = false) {
    const msgDiv = document.createElement('div');
    msgDiv.className = 'message' + (isSystem ? ' message-system' : ' message-user');

    const contentDiv = document.createElement('div');
    contentDiv.className = 'message-content';
    
    if (isSystem && window.marked) {
        contentDiv.innerHTML = chatRenderer.formatMarkdown(content);
    } else {
        contentDiv.innerHTML = `<p>${content}</p>`;
    }

    msgDiv.appendChild(contentDiv);
    chatMessages.appendChild(msgDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;
    return contentDiv;
}

function showTypingIndicator() {
    const indicator = chatRenderer.createTypingIndicator();
    indicator.id = 'home-chat-typing';
    chatMessages.appendChild(indicator);
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

function hideTypingIndicator() {
    const indicator = document.getElementById('home-chat-typing');
    if (indicator) indicator.remove();
}

async function sendMessage() {
    const text = chatInput.value.trim();
    if (!text) return;

    chatInput.disabled = true;
    chatSendBtn.disabled = true;

    addMessage(text, false);
    chatInput.value = '';

    chatHistory.push({ role: 'user', content: text });

    showTypingIndicator();

    try {
        const response = await fetch(API_URLS.webChat, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({
                message: text,
                session_id: chatSessionId,
                context: { history: chatHistory }
            })
        });

        const data = await response.json();
        hideTypingIndicator();

        if (response.ok && data.reply) {
            chatSessionId = data.session_id;

            await chatRenderer.renderAIMessage(chatMessages, data, () => {
                chatMessages.scrollTop = chatMessages.scrollHeight;
            });
            
            chatHistory.push({ role: 'assistant', content: data.reply });
        } else {
            const errorMsg = data.error || 'AI 服务暂时不可用';
            addMessage(`⚠️ ${errorMsg}<br><br>请前往 <a href="${API_URLS.aiProviderManage}">AI 接口管理</a> 配置 AI 提供商。`, true);
        }
    } catch (error) {
        hideTypingIndicator();
        addMessage(`❌ 网络错误: ${error.message}`, true);
    } finally {
        chatInput.disabled = false;
        chatSendBtn.disabled = false;
        chatInput.focus();
    }
}

async function executeSuggestedAction(action) {
    showTypingIndicator();
    
    try {
        const response = await fetch(API_URLS.webChat, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({
                message: action.command || action.intent,
                session_id: chatSessionId,
                context: { 
                    history: chatHistory,
                    execute_capability: action.capability_key,
                    action_type: action.action_type
                }
            })
        });

        const data = await response.json();
        hideTypingIndicator();

        if (response.ok && data.reply) {
            chatSessionId = data.session_id;
            
            await chatRenderer.renderAIMessage(chatMessages, data, () => {
                chatMessages.scrollTop = chatMessages.scrollHeight;
            });
            
            chatHistory.push({ role: 'assistant', content: data.reply });
        } else {
            addMessage(`⚠️ 执行失败: ${data.error || '未知错误'}`, true);
        }
    } catch (error) {
        hideTypingIndicator();
        addMessage(`❌ 执行错误: ${error.message}`, true);
    }
}

function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function getAlphaScopeMode() {
    const scopeInput = document.getElementById('alphaScopeMode');
    if (scopeInput) {
        return scopeInput.value === 'general' ? 'general' : 'portfolio';
    }
    return DASHBOARD_ALPHA_DEFAULTS.alphaScope === 'general' ? 'general' : 'portfolio';
}

function getAlphaPortfolioId() {
    const portfolioSelect = document.getElementById('alphaPortfolioSelect');
    return portfolioSelect ? portfolioSelect.value : DASHBOARD_ALPHA_DEFAULTS.portfolioId;
}

function getAlphaPoolMode() {
    const poolModeSelect = document.getElementById('alphaPoolModeSelect');
    return poolModeSelect ? poolModeSelect.value : DASHBOARD_ALPHA_DEFAULTS.poolMode;
}

function refreshAlphaHomepageFallback(delayMs = 300) {
    window.setTimeout(() => {
        window.location.reload();
    }, delayMs);
}

function hasInlineAlphaStocksTarget() {
    return Boolean(document.getElementById('alphaStocksTable'));
}

function updateAlphaScopeControls() {
    const scope = getAlphaScopeMode();
    const generalTab = document.getElementById('alphaScopeGeneralTab');
    const portfolioTab = document.getElementById('alphaScopePortfolioTab');
    const portfolioSelect = document.getElementById('alphaPortfolioSelect');
    const refreshBtn = document.getElementById('alphaRealtimeRefreshBtn');

    if (generalTab) {
        generalTab.classList.toggle('active', scope === 'general');
    }
    if (portfolioTab) {
        portfolioTab.classList.toggle('active', scope === 'portfolio');
    }
    if (portfolioSelect) {
        portfolioSelect.disabled = scope === 'general';
    }
    if (refreshBtn) {
        refreshBtn.innerHTML = scope === 'general'
            ? '<span>⚡ 刷新通用排名</span>'
            : '<span>⚡ 触发专属推理</span>';
    }
}

function setAlphaScopeMode(scope) {
    const scopeInput = document.getElementById('alphaScopeMode');
    if (scopeInput) {
        scopeInput.value = scope === 'general' ? 'general' : 'portfolio';
    }
    updateAlphaScopeControls();
    reloadAlphaStocksTable(10);
}

function reloadAlphaStocksTable(topN = 10) {
    const target = document.getElementById('alphaStocksTable');
    const alphaScope = getAlphaScopeMode();
    const portfolioId = getAlphaPortfolioId();
    const poolMode = getAlphaPoolMode();
    const query = new URLSearchParams({ top_n: String(topN), alpha_scope: alphaScope });
    if (alphaScope === 'portfolio' && portfolioId) {
        query.set('portfolio_id', portfolioId);
    }
    if (alphaScope === 'portfolio' && poolMode) {
        query.set('pool_mode', poolMode);
    }
    if (window.htmx && target) {
        window.htmx.ajax('GET', `${API_URLS.alphaStocks}?${query.toString()}`, {
            target: '#alphaStocksTable',
            swap: 'innerHTML',
        });
        return;
    }
    refreshAlphaHomepageFallback();
}

let alphaAutoRefreshTimer = null;

function scheduleAlphaAutoRefreshFromPanel() {
    const panel = document.querySelector('#alphaStocksTable .alpha-homepage-panel');
    const statusNode = document.getElementById('alphaRefreshStatus');
    if (!panel) {
        return;
    }

    const refreshStatus = panel.dataset.alphaRefreshStatus || '';
    const shouldPoll = refreshStatus === 'queued' || refreshStatus === 'recently_queued';
    if (!shouldPoll) {
        return;
    }

    const pollAfterMs = Number.parseInt(panel.dataset.alphaPollAfterMs || '5000', 10) || 5000;
    if (statusNode) {
        statusNode.textContent = '后台正在生成账户池 Alpha cache，稍后自动刷新...';
        statusNode.classList.remove('is-error');
    }
    if (alphaAutoRefreshTimer) {
        window.clearTimeout(alphaAutoRefreshTimer);
    }
    alphaAutoRefreshTimer = window.setTimeout(() => {
        reloadAlphaStocksTable(10);
    }, pollAfterMs);
}

async function triggerAlphaRealtimeRefresh(topN = 10, triggerButton = null) {
    const refreshBtn = triggerButton || document.getElementById('alphaRealtimeRefreshBtn');
    const statusNode = document.getElementById('alphaRefreshStatus');
    const originalLabel = refreshBtn ? refreshBtn.innerHTML : '';
    const alphaScope = getAlphaScopeMode();

    if (refreshBtn) {
        refreshBtn.disabled = true;
        refreshBtn.innerHTML = '<span>⏳ 刷新中</span>';
    }
    if (statusNode) {
        statusNode.textContent = alphaScope === 'portfolio'
            ? '正在触发 Alpha 同步推理，请稍候...'
            : '正在触发 Alpha 刷新任务，请稍候...';
        statusNode.classList.remove('is-error');
    }

    try {
        const portfolioId = getAlphaPortfolioId();
        const poolMode = getAlphaPoolMode();
        if (alphaScope === 'portfolio' && !portfolioId) {
            throw new Error('账户专属 Alpha 推理必须先选择组合。');
        }
        const body = new URLSearchParams({
            top_n: String(topN),
            alpha_scope: alphaScope,
        });
        if (alphaScope === 'portfolio') {
            body.set('sync', '1');
            body.set('portfolio_id', portfolioId);
            body.set('pool_mode', poolMode);
        }
        const response = await fetch(API_URLS.alphaRefresh, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
                'X-CSRFToken': getCookie('csrftoken'),
            },
            body,
        });
        const data = await response.json();
        if (!response.ok || !data.success) {
            throw new Error(data.error || '触发 Alpha 实时刷新失败');
        }

        if (statusNode) {
            statusNode.textContent = data.message || 'Alpha 刷新完成。';
        }
        if (!hasInlineAlphaStocksTarget()) {
            refreshAlphaHomepageFallback(data.sync ? 0 : (data.poll_after_ms || 5000));
            return;
        }
        reloadAlphaStocksTable(topN);
        if (!data.sync) {
            window.setTimeout(() => reloadAlphaStocksTable(topN), data.poll_after_ms || 5000);
        }
    } catch (error) {
        if (statusNode) {
            statusNode.textContent = error.message;
            statusNode.classList.add('is-error');
        }
    } finally {
        if (refreshBtn) {
            refreshBtn.disabled = false;
            refreshBtn.innerHTML = originalLabel;
        }
    }
}

async function discardAlphaPendingRequest(requestId) {
    if (!requestId) {
        return;
    }
    const confirmed = window.confirm('确认丢弃这条待执行请求吗？记录会保留，状态改为已取消。');
    if (!confirmed) {
        return;
    }

    try {
        const response = await fetch(
            `${API_URLS.decisionRequestCancelBase}${encodeURIComponent(requestId)}/cancel/`,
            {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken'),
                },
                body: JSON.stringify({
                    reason: '用户在 Dashboard 丢弃待执行请求',
                }),
            }
        );
        const data = await response.json();
        if (!response.ok || !data.success) {
            throw new Error(data.error || '丢弃待执行请求失败');
        }
        reloadAlphaStocksTable(10);
        window.setTimeout(() => window.location.reload(), 300);
    } catch (error) {
        window.alert(error.message);
    }
}

document.addEventListener('DOMContentLoaded', () => {
    updateAlphaScopeControls();
    scheduleAlphaAutoRefreshFromPanel();
});
document.body.addEventListener('htmx:afterSwap', (event) => {
    if (event.target && event.target.id === 'alphaStocksTable') {
        updateAlphaScopeControls();
        scheduleAlphaAutoRefreshFromPanel();
    }
});

chatInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        chatSendBtn.click();
    }
});

chatSendBtn.addEventListener('click', sendMessage);

// 快捷提问
document.querySelectorAll('.suggestion-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        chatInput.value = btn.dataset.query;
        chatSendBtn.click();
    });
});

// 定期刷新数据
setInterval(() => {
    window.fetchJsonOrThrow('/api/regime/current/')
        .then(() => {
            // 只刷新关键指标，不刷新整个页面
            console.log('数据已更新');
        })
        .catch(error => {
            console.warn('Failed to refresh regime data:', error);
        });
}, 300000); // 每5分钟刷新一次

// ========================================
// Alpha Provider 状态渲染
// ========================================

// 渲染 Provider 状态
function renderProviderStatus() {
    const providerDataElement = document.getElementById('providerData');
    if (!providerDataElement) return;

    const providerData = JSON.parse(providerDataElement.textContent);
    const container = document.getElementById('providerListContainer');

    if (!container) return;

    if (!providerData || !providerData.providers) {
        container.innerHTML = '<div class="empty-state"><p>暂无 Provider 状态数据</p></div>';
        return;
    }

    const providerNames = {
        'qlib': 'Qlib',
        'cache': '缓存',
        'simple': '简单因子',
        'etf': 'ETF 降级'
    };

    let html = '';
    for (const [name, info] of Object.entries(providerData.providers)) {
        const status = info.status || 'unknown';
        const metrics = providerData.metrics?.[name] || null;
        const message = info.message || '';
        const statusLabels = {
            available: '✓ 可用',
            degraded: '⚠ 降级',
            registered: '◌ 已注册',
            unavailable: '✗ 不可用',
        };

        html += `
            <div class="provider-item provider-${status}">
                <div class="provider-header">
                    <span class="provider-name">${providerNames[name] || name}</span>
                    <span class="provider-status-badge status-${status}">
                        ${statusLabels[status] || '？未知'}
                    </span>
                </div>
                ${message ? `<div class="provider-message">${message}</div>` : ''}
                ${metrics ? `
                    <div class="provider-metrics">
                        <span class="metric">成功率: <strong>${metrics.success_rate.toFixed(1)}%</strong></span>
                        <span class="metric">延迟: <strong>${metrics.latency_ms}ms</strong></span>
                    </div>
                ` : ''}
            </div>
        `;
    }

    container.innerHTML = html;
}

// 刷新 Provider 状态
async function refreshProviderStatus() {
    const container = document.getElementById('providerListContainer');
    if (!container) return;

    container.innerHTML = '<div class="loading-state"><p>刷新中...</p></div>';

    try {
        const response = await fetch('/api/dashboard/alpha/provider-status/');
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
        }
        const result = await response.json();

        if (result.success && result.data) {
            // 更新 providerData 元素
            const providerDataElement = document.getElementById('providerData');
            if (providerDataElement) {
                providerDataElement.textContent = JSON.stringify(result.data);
            }
            renderProviderStatus();
        }
    } catch (error) {
        container.innerHTML = '<div class="error-state"><p>刷新失败: ' + error.message + '</p></div>';
    }
}

// 页面加载时渲染 Provider 状态
document.addEventListener('DOMContentLoaded', renderProviderStatus);

// ========================================
// Qlib 状态检测
// ========================================

async function checkQlibStatus() {
    const indicator = document.getElementById('qlibStatusIndicator');
    const desc = document.getElementById('qlibStatusDesc');

    if (!indicator || !desc) return;

    try {
        const response = await fetch('/api/dashboard/alpha/provider-status/');
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
        }
        const result = await response.json();

        if (result.success && result.data && result.data.providers) {
            const qlibProvider = result.data.providers.qlib;
            const qlibMetrics = result.data.metrics?.qlib;

            if (qlibProvider) {
                if (qlibProvider.status === 'available') {
                    indicator.className = 'status-indicator status-ok';
                    desc.innerHTML = `✓ 可用 (成功率: ${qlibMetrics?.success_rate.toFixed(1) || 0}%)`;
                } else if (qlibProvider.status === 'degraded') {
                    indicator.className = 'status-indicator status-warning';
                    const msg = qlibProvider.message || '降级运行中';
                    desc.innerHTML = `⚠ ${msg}`;
                } else if (qlibProvider.status === 'registered') {
                    indicator.className = 'status-indicator status-warning';
                    desc.innerHTML = '◌ 已注册，未做实时健康检查';
                } else {
                    indicator.className = 'status-indicator status-error';
                    const msg = qlibProvider.message || '不可用';
                    desc.innerHTML = `✗ ${msg}`;
                }
            } else {
                indicator.className = 'status-indicator status-warning';
                desc.textContent = '⚠ 未安装 (使用降级方案)';
            }
        }
    } catch (error) {
        indicator.className = 'status-indicator status-warning';
        desc.textContent = '⚠ 状态未知';
    }
}

// 页面加载时检测 Qlib 状态
document.addEventListener('DOMContentLoaded', checkQlibStatus);

// ========================================
// 图表初始化 (ECharts)
// ========================================

// 资产配置饼图
let allocationChartInstance = null;
const allocationEl = document.getElementById('allocationChart');
const allocationEmptyEl = document.getElementById('allocationEmpty');

if (allocationEl) {
    allocationChartInstance = echarts.init(allocationEl);
    window.addEventListener('resize', () => { if (allocationChartInstance) allocationChartInstance.resize(); });
}

function renderAllocationChart(chartData) {
    if (!allocationEl) return;
    const dataKeys = Object.keys(chartData || {});
    const dataValues = Object.values(chartData || {});
    const hasData = dataValues.some(v => v > 0);

    if (hasData) {
        allocationEl.style.display = '';
        allocationEmptyEl.style.display = 'none';
        allocationChartInstance.setOption({
            tooltip: {
                trigger: 'item',
                formatter: '{b}: ¥{c} ({d}%)'
            },
            legend: {
                top: '5%',
                left: 'center'
            },
            series: [{
                type: 'pie',
                radius: ['40%', '70%'],
                data: dataKeys.map((name, i) => ({ name, value: dataValues[i] })),
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    formatter: '{b}\n{d}%'
                }
            }]
        }, true);
    } else {
        allocationEl.style.display = 'none';
        allocationEmptyEl.style.display = '';
    }
}

// 初始渲染
renderAllocationChart({{ allocation_data|safe }});

// 收益趋势图
let performanceChartInstance = null;
const performanceEl = document.getElementById('performanceChart');
const performanceEmptyEl = document.getElementById('performanceEmpty');

if (performanceEl) {
    performanceChartInstance = echarts.init(performanceEl);
    window.addEventListener('resize', () => { if (performanceChartInstance) performanceChartInstance.resize(); });
}

function renderPerformanceChart(performanceData) {
    if (!performanceEl) return;
    const hasData = performanceData && performanceData.length > 0;

    if (hasData) {
        performanceEl.style.display = '';
        performanceEmptyEl.style.display = 'none';
        performanceChartInstance.setOption({
            tooltip: {
                trigger: 'axis',
                formatter: '{b}<br/>收益率: {c}%'
            },
            xAxis: {
                type: 'category',
                data: performanceData.map(d => d.date),
                axisLine: { lineStyle: { color: '#999' } },
                axisLabel: { color: '#666' }
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    formatter: '{value}%'
                },
                axisLine: { lineStyle: { color: '#999' } },
                splitLine: { lineStyle: { color: '#eee' } }
            },
            series: [{
                type: 'line',
                data: performanceData.map(d => d.return_pct),
                smooth: true,
                symbolSize: 6,
                lineStyle: {
                    color: '#3366CC',
                    width: 2
                },
                itemStyle: {
                    color: '#3366CC'
                },
                areaStyle: {
                    color: {
                        type: 'linear',
                        x: 0, y: 0, x2: 0, y2: 1,
                        colorStops: [
                            { offset: 0, color: 'rgba(51, 102, 204, 0.3)' },
                            { offset: 1, color: 'rgba(51, 102, 204, 0.05)' }
                        ]
                    }
                },
                markPoint: {
                    data: [
                        { type: 'max', name: '最高' },
                        { type: 'min', name: '最低' }
                    ]
                }
            }]
        }, true);
    } else {
        performanceEl.style.display = 'none';
        performanceEmptyEl.style.display = '';
    }
}

// 初始渲染
renderPerformanceChart({{ performance_data|safe }});

// IC/ICIR 趋势图（Alpha 可视化）
const icTrendsCtx = document.getElementById('icTrendsChart');
if (icTrendsCtx) {
    const icTrendsDataElement = document.getElementById('icTrendsData');
    const icTrendsData = icTrendsDataElement ? JSON.parse(icTrendsDataElement.textContent) : [];
    if (icTrendsData && icTrendsData.length > 0) {
        const icChart = echarts.init(icTrendsCtx);

        // 过滤掉空数据
        const validData = icTrendsData.filter(d => d.ic !== null);

        icChart.setOption({
            tooltip: {
                trigger: 'axis',
                formatter: function(params) {
                    if (!params || params.length === 0) return '';
                    const p = params[0];
                    return `${p.axisValue}<br/>IC: ${p.data[1]}<br/>ICIR: ${p.data[2]}`;
                }
            },
            legend: {
                data: ['IC', 'ICIR'],
                top: 5,
                textStyle: { fontSize: 11 }
            },
            grid: {
                left: 50,
                right: 20,
                top: 40,
                bottom: 30
            },
            xAxis: {
                type: 'category',
                data: validData.map(d => d.date.substring(5)),  // 只显示 MM-DD
                axisLine: { lineStyle: { color: '#ddd' } },
                axisLabel: {
                    color: '#666',
                    fontSize: 10,
                    rotate: 45
                }
            },
            yAxis: {
                type: 'value',
                name: 'IC / ICIR',
                nameTextStyle: { fontSize: 10 },
                axisLabel: {
                    formatter: '{value}',
                    fontSize: 10
                },
                axisLine: { lineStyle: { color: '#ddd' } },
                splitLine: { lineStyle: { color: '#f0f0f0' } }
            },
            series: [
                {
                    name: 'IC',
                    type: 'line',
                    data: validData.map(d => [d.date, d.ic]),
                    smooth: true,
                    symbolSize: 4,
                    lineStyle: {
                        color: '#667eea',
                        width: 1.5
                    },
                    itemStyle: {
                        color: '#667eea'
                    }
                },
                {
                    name: 'ICIR',
                    type: 'line',
                    data: validData.map(d => [d.date, d.icir]),
                    smooth: true,
                    symbolSize: 4,
                    lineStyle: {
                        color: '#f59e0b',
                        width: 1.5
                    },
                    itemStyle: {
                        color: '#f59e0b'
                    }
                }
            ]
        });
        window.addEventListener('resize', () => icChart.resize());

        // 周期选择器事件
        const periodSelect = document.getElementById('icPeriodSelect');
        if (periodSelect) {
            periodSelect.addEventListener('change', function() {
                window.fetchJsonOrThrow(`/api/dashboard/alpha/ic-trends/?days=${this.value}`)
                    .then(response => {
                        if (response.success && response.data) {
                            const newValidData = response.data.filter(d => d.ic !== null);
                            icChart.setOption({
                                xAxis: {
                                    data: newValidData.map(d => d.date.substring(5))
                                },
                                series: [
                                    { data: newValidData.map(d => [d.date, d.ic]) },
                                    { data: newValidData.map(d => [d.date, d.icir]) }
                                ]
                            });
                        }
                    })
                    .catch(error => {
                        console.warn('Failed to refresh IC trends:', error);
                    });
            });
        }
    } else {
        icTrendsCtx.parentElement.innerHTML = '<p class="text-muted" style="font-size: 12px;">暂无 IC 数据</p>';
    }
}

// ========================================
// 图表账户切换（资产配置 + 收益趋势）
// ========================================

const chartAccountFilter = document.getElementById('chartAccountFilter');
if (chartAccountFilter) {
    chartAccountFilter.addEventListener('change', function() {
        const accountId = this.value;
        const selectedText = this.options[this.selectedIndex].text;

        // 更新图表标签
        const allocLabel = document.getElementById('allocationAccountLabel');
        if (allocLabel) allocLabel.textContent = selectedText;
        const perfLabel = document.getElementById('performanceAccountLabel');
        if (perfLabel) perfLabel.textContent = selectedText;

        const qs = accountId ? '?account_id=' + accountId : '';

        // 刷新资产配置图表
        window.fetchJsonOrThrow('/api/dashboard/allocation/' + qs)
            .then(response => {
                if (response.success && response.data) {
                    renderAllocationChart(response.data);
                }
            })
            .catch(err => console.warn('Failed to refresh allocation chart:', err));

        // 刷新收益趋势图表
        window.fetchJsonOrThrow('/api/dashboard/performance/' + qs)
            .then(response => {
                if (response.success && response.data) {
                    renderPerformanceChart(response.data);
                }
            })
            .catch(err => console.warn('Failed to refresh performance chart:', err));
    });
}

// ========================================
// 持仓排序功能
// ========================================

document.querySelectorAll('.sortable').forEach(th => {
    th.style.cursor = 'pointer';
    th.addEventListener('click', function() {
        const sortBy = this.dataset.sort;
        const table = this.closest('table');
        const tbody = table.querySelector('tbody');
        const rows = Array.from(tbody.querySelectorAll('tr'));

        // 检查当前排序方向
        const currentSort = tbody.dataset.sort;
        const currentOrder = tbody.dataset.order || 'asc';
        const newOrder = (currentSort === sortBy && currentOrder === 'asc') ? 'desc' : 'asc';

        rows.sort((a, b) => {
            let aVal, bVal;

            switch(sortBy) {
                case 'code':
                    aVal = a.querySelector('td:first-child').textContent.trim();
                    bVal = b.querySelector('td:first-child').textContent.trim();
                    return aVal.localeCompare(bVal);
                case 'name':
                    aVal = a.children[1].textContent.trim();
                    bVal = b.children[1].textContent.trim();
                    return aVal.localeCompare(bVal, 'zh-CN');
                case 'market_value':
                    aVal = parseFloat(a.children[2].textContent.replace(/[¥,]/g, ''));
                    bVal = parseFloat(b.children[2].textContent.replace(/[¥,]/g, ''));
                    break;
                case 'pnl':
                    aVal = parseFloat(a.children[3].textContent.replace(/[¥,]/g, ''));
                    bVal = parseFloat(b.children[3].textContent.replace(/[¥,]/g, ''));
                    break;
                case 'pnl_pct':
                    aVal = parseFloat(a.children[4].textContent.replace('%', ''));
                    bVal = parseFloat(b.children[4].textContent.replace('%', ''));
                    break;
            }

            if (typeof aVal === 'number') {
                return newOrder === 'asc' ? aVal - bVal : bVal - aVal;
            }
            return 0;
        });

        rows.forEach(row => tbody.appendChild(row));
        tbody.dataset.sort = sortBy;
        tbody.dataset.order = newOrder;

        // 更新排序指示器
        table.querySelectorAll('.sortable').forEach(h => {
            h.classList.remove('sort-asc', 'sort-desc');
        });
        this.classList.add(newOrder === 'asc' ? 'sort-asc' : 'sort-desc');
    });
});

// ========================================
// AI 聊天（统一入口，自动检测流式/普通响应）
// ========================================

chatSendBtn.onclick = async function() {
    const text = chatInput.value.trim();
    if (!text) return;

    chatInput.disabled = true;
    chatSendBtn.disabled = true;

    addMessage(text, false);
    chatInput.value = '';
    chatHistory.push({ role: 'user', content: text });

    // 添加临时消息
    const tempMsgDiv = document.createElement('div');
    tempMsgDiv.className = 'message message-system';
    const tempContentDiv = document.createElement('div');
    tempContentDiv.className = 'message-content';
    tempContentDiv.innerHTML = '<p class="streaming-text">...</p>';
    tempMsgDiv.appendChild(tempContentDiv);
    chatMessages.appendChild(tempMsgDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;

    try {
        const response = await fetch(API_URLS.promptChat, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({
                message: text,
                session_id: chatSessionId,
                context: { history: chatHistory }
            })
        });

        if (!response.ok) {
            const data = await response.json();
            const errorMsg = data.error || 'AI 服务暂时不可用';
            tempContentDiv.innerHTML = `<p>⚠️ ${errorMsg}<br><br>请前往 <a href="${API_URLS.aiProviderManage}">AI 接口管理</a> 配置 AI 提供商。</p>`;
            return;
        }

        const contentType = response.headers.get('Content-Type') || '';

        if (contentType.includes('text/event-stream')) {
            // 流式响应
            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let fullReply = '';

            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                const chunk = decoder.decode(value);
                const lines = chunk.split('\n');

                for (const line of lines) {
                    if (line.startsWith('data: ')) {
                        try {
                            const data = JSON.parse(line.slice(6));
                            if (data.content) {
                                fullReply += data.content;
                                tempContentDiv.innerHTML = `<p>${fullReply}</p>`;
                                chatMessages.scrollTop = chatMessages.scrollHeight;
                            }
                            if (data.session_id) {
                                chatSessionId = data.session_id;
                            }
                        } catch (_) { /* skip malformed line */ }
                    }
                }
            }

            chatHistory.push({ role: 'assistant', content: fullReply });
        } else {
            // 普通 JSON 响应
            const data = await response.json();
            if (data.reply) {
                chatSessionId = data.session_id;
                tempContentDiv.innerHTML = `<p>${data.reply}</p>`;
                chatHistory.push({ role: 'assistant', content: data.reply });
            } else {
                const errorMsg = data.error || 'AI 服务暂时不可用';
                tempContentDiv.innerHTML = `<p>⚠️ ${errorMsg}</p>`;
            }
        }
    } catch (error) {
        tempContentDiv.innerHTML = `<p>❌ 网络错误: ${error.message}</p>`;
    } finally {
        chatMessages.scrollTop = chatMessages.scrollHeight;
        chatInput.disabled = false;
        chatSendBtn.disabled = false;
        chatInput.focus();
    }
};
</script>

<style>
/* 新增样式 */
.signal-name {
    color: var(--text-secondary);
    font-size: 13px;
    margin-left: 8px;
}

.sort-select {
    padding: 4px 8px;
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    font-size: 13px;
    background: var(--bg-primary);
    cursor: pointer;
}

.alpha-scope-tabs {
    display: inline-flex;
    gap: 4px;
    padding: 3px;
    border: 1px solid var(--border-color);
    border-radius: 999px;
    background: #f4f7fb;
}

.alpha-scope-tab {
    border: 0;
    border-radius: 999px;
    background: transparent;
    color: var(--text-secondary);
    cursor: pointer;
    font-size: 12px;
    font-weight: 700;
    padding: 5px 10px;
}

.alpha-scope-tab.active {
    background: #122c57;
    color: #fff;
}

.sortable {
    position: relative;
    user-select: none;
}

.sortable:hover {
    background-color: var(--bg-tertiary);
}

.sortable.sort-asc::after {
    content: ' ▲';
    position: absolute;
    right: 8px;
}

.sortable.sort-desc::after {
    content: ' ▼';
    position: absolute;
    right: 8px;
}

.streaming-text {
    color: var(--text-muted);
}

.account-overview-section {
    background: var(--bg-secondary);
    border-radius: var(--radius-md);
    padding: 20px;
    margin-bottom: 20px;
}

.account-tag-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 16px;
}

.account-tag-card {
    display: block;
    background: var(--bg-primary);
    border: 1px solid var(--border-color);
    border-radius: 14px;
    padding: 16px;
    text-decoration: none;
    color: inherit;
    transition: transform 0.18s ease, border-color 0.18s ease, box-shadow 0.18s ease;
}

.account-tag-card:hover {
    transform: translateY(-2px);
    border-color: var(--accent-color);
    box-shadow: 0 10px 24px rgba(15, 23, 42, 0.08);
}

.account-tag-card-real {
    border-left: 4px solid #2563eb;
}

.account-tag-card-simulated {
    border-left: 4px solid #14b8a6;
}

.account-tag-topline,
.account-tag-meta {
    display: flex;
    justify-content: space-between;
    gap: 12px;
    align-items: center;
}

.account-tag-topline {
    margin-bottom: 10px;
}

.account-type-badge,
.account-status {
    font-size: 12px;
    font-weight: 600;
    padding: 4px 10px;
    border-radius: 999px;
}

.account-type-badge {
    background: var(--bg-tertiary);
    color: var(--text-secondary);
}

.account-status.is-active {
    background: rgba(34, 197, 94, 0.12);
    color: #15803d;
}

.account-status.is-inactive {
    background: rgba(148, 163, 184, 0.18);
    color: #475569;
}

.account-tag-name {
    font-size: 18px;
    font-weight: 700;
    margin-bottom: 8px;
}

.account-tag-assets {
    font-size: 24px;
    font-weight: 700;
    margin-bottom: 8px;
}

.account-tag-meta {
    color: var(--text-secondary);
    font-size: 12px;
    margin-bottom: 10px;
}

.account-tag-return {
    font-size: 13px;
    font-weight: 600;
}

/* 响应式调整 */
@media (max-width: 1200px) {
    .content-row {
        flex-direction: column;
    }

    .content-card.half {
        width: 100%;
    }

    .home-chat {
        position: fixed;
        right: 0;
        top: var(--header-height);
        bottom: 0;
        width: 320px;
        transform: translateX(100%);
        transition: transform 0.3s;
        z-index: 999;
    }

    .home-chat.open {
        transform: translateX(0);
    }
}

@media (max-width: 768px) {
    .home-layout {
        flex-direction: column;
    }

    .home-sidebar {
        width: 100%;
        height: auto;
    }

    .metrics-grid {
        grid-template-columns: 1fr;
    }
}

/* 资产配置建议样式 */
.allocation-advice-section {
    background: var(--bg-secondary);
    border-radius: var(--radius-md);
    padding: 20px;
    margin-bottom: 20px;
}

.allocation-advice-content {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.allocation-compare {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 20px;
}

.allocation-col {
    flex: 1;
}

.allocation-col h3 {
    font-size: 16px;
    margin-bottom: 12px;
    color: var(--text-secondary);
}

.allocation-bars {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.allocation-bar-item {
    display: flex;
    align-items: center;
    gap: 10px;
}

.bar-label {
    min-width: 80px;
    font-size: 13px;
    color: var(--text-secondary);
}

.bar-track {
    flex: 1;
    height: 20px;
    background: var(--bg-tertiary);
    border-radius: 4px;
    overflow: hidden;
}

.bar-fill {
    height: 100%;
    transition: width 0.3s ease;
}

.bar-current {
    background: linear-gradient(90deg, #A7C7F7, #7BA3D4);
}

.bar-target {
    background: linear-gradient(90deg, #C8E6C9, #81C784);
}

.bar-value {
    min-width: 45px;
    text-align: right;
    font-size: 13px;
    font-weight: 600;
}

.allocation-arrow {
    font-size: 24px;
    color: var(--text-muted);
}

.allocation-summary {
    background: var(--bg-tertiary);
    padding: 15px;
    border-radius: var(--radius-sm);
}

.allocation-summary p {
    margin: 0 0 10px 0;
    line-height: 1.6;
}

.expected-metrics {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
}

.expected-metrics span {
    font-size: 13px;
    color: var(--text-secondary);
}

.advice-badge {
    padding: 4px 12px;
    background: var(--primary-color);
    color: white;
    border-radius: var(--radius-sm);
    font-size: 13px;
}

.trade-actions {
    background: var(--bg-tertiary);
    padding: 15px;
    border-radius: var(--radius-sm);
}

.trade-actions h4 {
    margin: 0 0 12px 0;
    font-size: 15px;
}

.action-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.action-item {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    padding: 10px;
    background: var(--bg-secondary);
    border-radius: var(--radius-sm);
}

.action-badge {
    padding: 3px 8px;
    border-radius: var(--radius-sm);
    font-size: 11px;
    font-weight: bold;
    min-width: 50px;
    text-align: center;
}

.badge-buy {
    background: var(--color-rise-soft);
    color: var(--color-rise-strong);
}

.badge-sell {
    background: var(--color-fall-soft);
    color: var(--color-fall-strong);
}

.action-details {
    flex: 1;
}

.action-main {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 4px;
}

.action-amount {
    margin-left: auto;
    font-weight: 600;
    color: var(--primary-color);
}

.action-reason {
    font-size: 13px;
    color: var(--text-muted);
}

/* 决策平面样式 */
.decision-plane-section {
    margin-bottom: 20px;
}

.decision-plane-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
}

.decision-card {
    background: var(--bg-secondary);
    border-radius: var(--radius-md);
    border: 1px solid var(--border-color);
    overflow: hidden;
    transition: all 0.3s ease;
}

.decision-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.decision-card.beta-gate {
    border-top: 3px solid #667eea;
}

.decision-card.alpha-panel {
    border-top: 3px solid #f59e0b;
}

.decision-card.quota {
    border-top: 3px solid #10b981;
}

.decision-card-header {
    padding: 16px;
    display: flex;
    align-items: center;
    gap: 8px;
    border-bottom: 1px solid var(--border-color);
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.05), rgba(118, 75, 162, 0.05));
}

.decision-icon {
    font-size: 20px;
}

.decision-title {
    flex: 1;
    font-weight: 600;
    font-size: 14px;
}

.decision-link {
    color: var(--primary-color);
    text-decoration: none;
    font-size: 13px;
}

.decision-link:hover {
    text-decoration: underline;
}

.decision-card-body {
    padding: 16px;
}

.decision-status {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    font-size: 13px;
}

.status-label {
    color: var(--text-muted);
}

.status-value {
    font-weight: 600;
    color: var(--text-primary);
}

.decision-stats {
    display: flex;
    justify-content: space-around;
    gap: 12px;
}

.decision-stat {
    text-align: center;
    flex: 1;
}

.decision-stat .stat-value {
    font-size: 24px;
    font-weight: 700;
    color: var(--primary-color);
}

.decision-stat .stat-label {
    font-size: 12px;
    color: var(--text-muted);
}

.quota-progress {
    margin-top: 12px;
}

.quota-progress-bar {
    height: 8px;
    background: var(--border-color);
    border-radius: 4px;
    overflow: hidden;
    position: relative;
}

.quota-progress-bar::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(90deg, #667eea, #764ba2);
    border-radius: 4px;
}

@media (max-width: 768px) {
    .decision-plane-grid {
        grid-template-columns: 1fr;
    }
}

/* ========================================
   Alpha 可视化样式（新增）
   ======================================== */

.alpha-visualization-section {
    background: var(--bg-secondary);
    border-radius: var(--radius-md);
    padding: 20px;
    margin-bottom: 20px;
    border: 1px solid var(--border-color);
}

/* 数据源标识徽章 */
.data-source-badges {
    display: flex;
    gap: 8px;
    align-items: center;
    flex-wrap: wrap;
}

.ds-badge {
    padding: 4px 10px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    gap: 4px;
    cursor: help;
    transition: all 0.2s ease;
}

.ds-badge:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0,0,0,0.15);
}

.ds-qlib {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
}

.ds-cache {
    background: #E0F2F1;
    color: #00695C;
}

.ds-simple {
    background: #FFF8E1;
    color: #FF8F00;
}

.ds-etf {
    background: #ECEFF1;
    color: #546E7A;
}

/* 数据源说明栏 */
.data-source-info {
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.05), rgba(118, 75, 162, 0.05));
    border: 1px solid rgba(102, 126, 234, 0.2);
    border-radius: 8px;
    padding: 12px 16px;
    margin-bottom: 16px;
    display: flex;
    align-items: flex-start;
    gap: 10px;
    font-size: 12px;
    line-height: 1.6;
}

.info-icon {
    font-size: 16px;
    flex-shrink: 0;
}

.info-text {
    flex: 1;
    color: var(--text-secondary);
}

.info-text strong {
    color: var(--text-primary);
    margin-right: 8px;
}

.ds-tag {
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 10px;
    font-weight: 600;
    margin: 0 4px;
}

.ds-qlib-tag {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
}

.ds-cache-tag {
    background: #E0F2F1;
    color: #00695C;
}

.ds-simple-tag {
    background: #FFF8E1;
    color: #FF8F00;
}

.ds-etf-tag {
    background: #ECEFF1;
    color: #546E7A;
}

.alpha-metrics-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    margin-bottom: 20px;
}

.alpha-metric-card {
    background: var(--bg-tertiary);
    border-radius: var(--radius-sm);
    padding: 16px;
    display: flex;
    align-items: center;
    gap: 12px;
    border-left: 3px solid var(--primary-color);
    transition: all 0.3s ease;
}

.alpha-metric-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.alpha-metric-card .metric-icon {
    font-size: 24px;
}

.alpha-metric-card .metric-content {
    flex: 1;
}

.alpha-metric-card .metric-title {
    font-size: 12px;
    color: var(--text-muted);
    margin-bottom: 4px;
}

.alpha-metric-card .metric-value {
    font-size: 20px;
    font-weight: 700;
    color: var(--text-primary);
}

.alpha-metric-card .metric-subtitle {
    font-size: 11px;
    color: var(--text-muted);
}

.alpha-summary-section {
    background:
        radial-gradient(circle at top right, rgba(37, 99, 235, 0.08), transparent 32%),
        var(--bg-secondary);
}

.alpha-summary-section .section-subtitle {
    margin: 6px 0 0;
    color: var(--text-secondary);
    font-size: 13px;
}

.alpha-summary-actions .refresh-btn {
    text-decoration: none;
    color: var(--text-primary);
}

.alpha-summary-grid {
    display: grid;
    grid-template-columns: minmax(0, 1.1fr) minmax(280px, 0.9fr);
    gap: 16px;
}

.alpha-summary-card {
    background: var(--bg-tertiary);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    padding: 16px;
}

.alpha-summary-card .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 12px;
    margin-bottom: 12px;
}

.alpha-summary-card .card-header h3 {
    margin: 0;
    font-size: 15px;
    color: var(--text-primary);
}

.alpha-summary-card .card-badge {
    padding: 4px 10px;
    background: rgba(18, 44, 87, 0.08);
    color: #122c57;
    border-radius: 999px;
    font-size: 11px;
    font-weight: 600;
    white-space: nowrap;
}

.alpha-summary-list,
.alpha-summary-meta {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.alpha-summary-item {
    display: grid;
    grid-template-columns: 56px minmax(0, 1fr) auto;
    align-items: center;
    gap: 12px;
    padding: 12px;
    border: 1px solid var(--border-color);
    border-radius: 12px;
    background: var(--bg-primary);
    color: inherit;
    text-decoration: none;
    transition: transform 0.18s ease, border-color 0.18s ease, box-shadow 0.18s ease;
}

.alpha-summary-item:hover {
    transform: translateY(-1px);
    border-color: var(--primary-color);
    box-shadow: 0 8px 18px rgba(15, 23, 42, 0.08);
}

.alpha-summary-rank {
    color: #122c57;
    font-weight: 700;
}

.alpha-summary-main {
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 3px;
}

.alpha-summary-main span,
.alpha-summary-meta span,
.alpha-summary-footer {
    color: var(--text-secondary);
    font-size: 12px;
}

.alpha-summary-score {
    font-weight: 700;
    color: var(--primary-color);
}

.alpha-summary-empty {
    margin: 0;
    color: var(--text-secondary);
    font-size: 13px;
}

.alpha-summary-meta span {
    display: inline-flex;
    justify-content: space-between;
    gap: 12px;
    padding: 10px 12px;
    background: var(--bg-primary);
    border-radius: 10px;
}

.alpha-summary-meta .alpha-summary-warning {
    color: #92400e;
    background: #fff7ed;
}

.alpha-summary-footer {
    margin-top: 12px;
    padding-top: 12px;
    border-top: 1px solid var(--border-color);
}

.alpha-content-row {
    display: grid;
    grid-template-columns: minmax(0, 1.7fr) minmax(320px, 1fr);
    gap: 16px;
    align-items: start;
}

.alpha-content-card {
    background: var(--bg-tertiary);
    border-radius: var(--radius-sm);
    overflow: hidden;
    min-width: 0;
}

.alpha-content-card .card-header {
    padding: 12px 16px;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.08), rgba(118, 75, 162, 0.08));
    border-bottom: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.alpha-content-card .card-header h3 {
    font-size: 14px;
    font-weight: 600;
    margin: 0;
    color: var(--text-primary);
}

.alpha-content-card .card-badge {
    padding: 4px 10px;
    background: var(--primary-color);
    color: white;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 600;
}

.alpha-card-actions {
    display: flex;
    align-items: center;
    gap: 12px;
}

.alpha-section-link {
    font-size: 12px;
    font-weight: 600;
    color: var(--primary-color);
    text-decoration: none;
}

.alpha-section-link:hover {
    text-decoration: underline;
}

.alpha-content-card .card-body {
    padding: 16px;
}

.alpha-stocks-card {
    min-height: 400px;
}

.alpha-stocks-card .card-body {
    padding: 12px 16px;
}

.alpha-content-right {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.provider-status-card {
    flex: 0 0 auto;
}

.factor-panel-card {
    flex: 0 0 auto;
}

.ic-trends-card {
    flex: 1;
    min-height: 280px;
}

.card-hint {
    font-size: 11px;
    color: var(--text-muted);
}

.alpha-factor-panel {
    display: flex;
    flex-direction: column;
    gap: 14px;
}

.factor-panel-header {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 12px;
}

.factor-panel-title {
    margin: 0;
    font-size: 16px;
    color: var(--text-primary);
}

.factor-panel-subtitle {
    margin-top: 4px;
    font-size: 12px;
    color: var(--text-secondary);
}

.factor-stock-name {
    margin-left: 8px;
    color: var(--text-muted);
}

.factor-panel-badges {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    justify-content: flex-end;
}

.factor-provider-badge,
.factor-count-badge {
    padding: 4px 10px;
    border-radius: 999px;
    font-size: 11px;
    font-weight: 600;
}

.factor-provider-badge {
    background: rgba(15, 23, 42, 0.08);
    color: var(--text-primary);
    text-transform: uppercase;
}

.factor-provider-qlib {
    background: rgba(102, 126, 234, 0.16);
    color: #4c51bf;
}

.factor-provider-simple {
    background: rgba(245, 158, 11, 0.18);
    color: #b45309;
}

.factor-provider-cache {
    background: rgba(20, 184, 166, 0.16);
    color: #0f766e;
}

.factor-provider-etf {
    background: rgba(100, 116, 139, 0.16);
    color: #475569;
}

.factor-provider-sell {
    background: rgba(239, 68, 68, 0.16);
    color: #b91c1c;
}

.factor-provider-reduce {
    background: rgba(245, 158, 11, 0.18);
    color: #b45309;
}

.factor-provider-hold {
    background: rgba(16, 185, 129, 0.16);
    color: #047857;
}

.factor-count-badge {
    background: rgba(15, 23, 42, 0.05);
    color: var(--text-secondary);
}

.factor-summary-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 10px;
}

.factor-summary-item {
    background: var(--bg-secondary);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    padding: 10px 12px;
}

.factor-detail-block {
    border: 1px solid var(--border-color);
    border-radius: 12px;
    background: var(--bg-secondary);
    padding: 12px;
}

.factor-detail-block h4 {
    margin: 0 0 10px;
    font-size: 13px;
    color: var(--text-primary);
}

.factor-detail-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 8px;
}

.factor-detail-grid div {
    min-width: 0;
}

.factor-detail-grid span {
    display: block;
    font-size: 10px;
    color: var(--text-muted);
    margin-bottom: 2px;
    text-transform: uppercase;
}

.factor-detail-grid strong {
    display: block;
    font-size: 12px;
    color: var(--text-primary);
    overflow-wrap: anywhere;
}

.factor-decision-block {
    border-radius: 12px;
    padding: 12px;
}

.factor-decision-block strong {
    display: block;
    margin-bottom: 4px;
}

.factor-decision-block p {
    margin: 0;
    font-size: 12px;
}

.factor-decision-blocked {
    background: #fff8e8;
    border: 1px solid #f2d08a;
    color: #7a5418;
}

.factor-decision-ready {
    background: #ecfdf3;
    border: 1px solid #b7e4c7;
    color: #166534;
}

.factor-explain-list {
    margin: 0;
    padding-left: 18px;
    font-size: 12px;
    color: var(--text-secondary);
}

.factor-explain-list li + li {
    margin-top: 4px;
}

.summary-label {
    display: block;
    font-size: 11px;
    color: var(--text-muted);
    margin-bottom: 4px;
}

.summary-value {
    font-size: 15px;
    font-weight: 700;
    color: var(--text-primary);
}

.factor-bars {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.factor-row-top {
    display: flex;
    justify-content: space-between;
    gap: 12px;
    margin-bottom: 6px;
    font-size: 12px;
}

.factor-name {
    color: var(--text-secondary);
    word-break: break-word;
}

.factor-value {
    font-weight: 700;
}

.factor-value-positive {
    color: #047857;
}

.factor-value-negative {
    color: #b91c1c;
}

.factor-track {
    width: 100%;
    height: 10px;
    border-radius: 999px;
    background: rgba(148, 163, 184, 0.16);
    overflow: hidden;
}

.factor-fill {
    height: 100%;
    border-radius: 999px;
}

.factor-fill-positive {
    background: linear-gradient(90deg, #10b981, #34d399);
}

.factor-fill-negative {
    background: linear-gradient(90deg, #f97316, #ef4444);
}

.factor-origin-note {
    font-size: 11px;
    color: var(--text-muted);
    border-top: 1px dashed var(--border-color);
    padding-top: 10px;
}

.factor-empty-state {
    min-height: 160px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 8px;
    text-align: center;
    color: var(--text-secondary);
}

.factor-empty-icon {
    font-size: 28px;
    color: var(--text-muted);
}

/* Provider 状态列表 */
.provider-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.provider-item {
    background: var(--bg-secondary);
    border-radius: 6px;
    padding: 12px;
    border-left: 3px solid transparent;
}

.provider-item.provider-available {
    border-left-color: #4CAF50;
}

.provider-item.provider-degraded {
    border-left-color: #FF9800;
}

.provider-item.provider-registered {
    border-left-color: #2196F3;
}

.provider-item.provider-unavailable {
    border-left-color: #F44336;
    opacity: 0.6;
}

.provider-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 8px;
}

.provider-name {
    font-weight: 600;
    font-size: 13px;
    color: var(--text-primary);
}

.provider-status-badge {
    padding: 3px 8px;
    border-radius: 4px;
    font-size: 10px;
    font-weight: 600;
}

.provider-status-badge.status-available {
    background: #E8F5E9;
    color: #2E7D32;
}

.provider-status-badge.status-degraded {
    background: #FFF3E0;
    color: #F57C00;
}

.provider-status-badge.status-registered {
    background: #E3F2FD;
    color: #1565C0;
}

.provider-status-badge.status-unavailable {
    background: #FFEBEE;
    color: #C62828;
}

.provider-message {
    font-size: 11px;
    color: var(--text-muted);
    margin-bottom: 8px;
    padding: 4px 8px;
    background: rgba(255, 152, 0, 0.1);
    border-radius: 4px;
}

.provider-metrics {
    display: flex;
    gap: 16px;
    font-size: 11px;
    color: var(--text-muted);
}

.provider-metrics .metric strong {
    color: var(--text-primary);
}

/* 刷新按钮 */
.header-actions {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
}

.refresh-btn {
    padding: 6px 12px;
    background: var(--bg-tertiary);
    border: 1px solid var(--border-color);
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
    display: flex;
    align-items: center;
    gap: 4px;
    transition: all 0.2s ease;
}

.refresh-btn:hover {
    background: var(--bg-secondary);
    border-color: var(--primary-color);
}

.refresh-btn:disabled {
    opacity: 0.65;
    cursor: wait;
}

.refresh-btn-realtime {
    background: #eef6ff;
    border-color: #b7d3ff;
    color: #174ea6;
}

.alpha-refresh-status {
    font-size: 12px;
    color: var(--text-muted);
}

.alpha-refresh-status.is-error {
    color: #c62828;
}

.mini-refresh-btn {
    background: none;
    border: none;
    cursor: pointer;
    font-size: 14px;
    padding: 4px;
    opacity: 0.7;
    transition: opacity 0.2s ease;
}

.mini-refresh-btn:hover {
    opacity: 1;
}

/* 周期选择器 */
.period-select {
    padding: 4px 8px;
    border: 1px solid var(--border-color);
    border-radius: 4px;
    font-size: 11px;
    background: var(--bg-primary);
    cursor: pointer;
}

/* Alpha 可视化响应式 */
@media (max-width: 1200px) {
    .alpha-content-row {
        grid-template-columns: 1fr;
    }

    .alpha-summary-grid {
        grid-template-columns: 1fr;
    }

    .alpha-content-right {
        flex-direction: row;
    }
}

@media (max-width: 768px) {
    .alpha-metrics-grid {
        grid-template-columns: repeat(2, 1fr);
    }

    .alpha-content-right {
        flex-direction: column;
    }
}

@media (max-width: 480px) {
    .alpha-metrics-grid {
        grid-template-columns: 1fr;
    }
}

/* Qlib 状态卡片样式 */
.status-qlib-card {
    border-left: 3px solid #667eea;
}

.qlib-badge {
    display: inline-block;
    padding: 2px 6px;
    background: rgba(102, 126, 234, 0.1);
    color: #667eea;
    border-radius: 4px;
    font-size: 10px;
    font-weight: 600;
    margin-left: 4px;
}

/* 状态指示器扩展样式 */
.status-indicator.status-warning {
    background: #FF9800;
    box-shadow: 0 0 8px rgba(255, 152, 0, 0.5);
}

.status-indicator.status-error {
    background: #F44336;
    box-shadow: 0 0 8px rgba(244, 67, 54, 0.5);
}

.alpha-content-card.alpha-exit-detail-highlight {
    border-color: #3756a4;
    box-shadow: 0 16px 40px rgba(55, 86, 164, 0.16);
    transition: box-shadow 0.24s ease, border-color 0.24s ease;
}

/* 响应式状态网格 */
@media (max-width: 768px) {
    .status-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}
</style>

<!-- Teaching Module Scripts -->
<script src="{% static 'js/teaching/teaching-modal.js' %}"></script>
<script src="{% static 'js/teaching/regime-calculator.js' %}"></script>
<script src="{% static 'js/teaching/policy-simulator.js' %}"></script>
<!-- Phase 2 & 3 Enhancements -->
<script src="{% static 'js/teaching/policy-simulator-enhanced.js' %}"></script>
<script src="{% static 'js/teaching/cases-library.js' %}"></script>
<script src="{% static 'js/teaching/learning-progress.js' %}"></script>
<script src="{% static 'js/teaching/interactive-charts.js' %}"></script>
<script src="{% static 'js/teaching/bilingual-support.js' %}"></script>

<!-- Teaching Modal Template -->
{% include "dashboard/teaching_modal.html" %}

<!-- Main Workflow Panel JS (WP-3) -->
<script src="{% static 'js/main-workflow.js' %}"></script>

<!-- Floating Widget Config -->
<script>
    // Load floating widget config from JSON file
    fetch('{% static "widgets/configs/dashboard_widget.json" %}')
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            return response.json();
        })
        .then(config => {
            window.floatingWidgetConfig = config;
            // Trigger initialization manually since DOM is already loaded
            if (window.initFloatingWidget) {
                window.initFloatingWidget(config);
            }
        })
        .catch(err => console.error('Failed to load widget config:', err));
</script>

{% endblock %}

{% block extra_js %}
<script>
(function () {
    const storageKey = 'dashboard:pulse-browser-notification-enabled';
    const toggle = document.getElementById('pulseNotifyToggle');
    const payloadNode = document.getElementById('browserNotificationPayload');
    const payload = payloadNode ? JSON.parse(payloadNode.textContent) : null;

    function updateToggle() {
        if (!toggle) {
            return;
        }
        const enabled = localStorage.getItem(storageKey) === '1';
        toggle.innerHTML = enabled ? '<span>🔔 Pulse 通知已开启</span>' : '<span>🔕 开启 Pulse 通知</span>';
    }

    async function ensurePermission() {
        if (!('Notification' in window)) {
            return false;
        }
        if (Notification.permission === 'granted') {
            return true;
        }
        if (Notification.permission === 'denied') {
            return false;
        }
        const result = await Notification.requestPermission();
        return result === 'granted';
    }

    async function toggleNotifications() {
        const enabled = localStorage.getItem(storageKey) === '1';
        if (enabled) {
            localStorage.setItem(storageKey, '0');
            updateToggle();
            return;
        }

        const permitted = await ensurePermission();
        if (permitted) {
            localStorage.setItem(storageKey, '1');
        }
        updateToggle();
    }

    function showNotificationIfNeeded() {
        if (!payload || !('Notification' in window)) {
            return;
        }
        if (localStorage.getItem(storageKey) !== '1' || Notification.permission !== 'granted') {
            return;
        }

        const dedupeKey = `dashboard:notified:${payload.tag}`;
        if (sessionStorage.getItem(dedupeKey) === '1') {
            return;
        }

        sessionStorage.setItem(dedupeKey, '1');
        new Notification(payload.title, {
            body: payload.body,
            tag: payload.tag,
        });
    }

    updateToggle();
    if (toggle) {
        toggle.addEventListener('click', toggleNotifications);
    }
    showNotificationIfNeeded();
})();

(function () {
    function getExitDetailTarget() {
        return document.getElementById('alpha-exit-detail');
    }

    function getExitDetailPanel() {
        return document.getElementById('alphaExitDetailPanel');
    }

    function showExitDetailHint(assetCode, message) {
        const panel = getExitDetailPanel();
        if (!panel || !panel.parentElement) {
            return;
        }

        panel.parentElement.querySelectorAll('[data-dashboard-exit-hint="true"]').forEach(node => node.remove());
        const hint = document.createElement('div');
        hint.className = 'app-notification-banner app-notification-banner-info';
        hint.style.marginBottom = '12px';
        hint.setAttribute('data-dashboard-exit-hint', 'true');
        hint.innerHTML = `<strong>已在右侧打开退出详情</strong><span style="margin-left:8px;">${message || `${assetCode} 的退出契约、recommendation 与调仓计划已加载在当前面板。`}</span>`;
        panel.parentElement.insertBefore(hint, panel);
    }

    function highlightExitDetailPanel() {
        const target = getExitDetailTarget();
        if (!target) {
            return;
        }
        target.scrollIntoView({ behavior: 'smooth', block: 'start' });
        target.classList.add('alpha-exit-detail-highlight');
        window.setTimeout(() => target.classList.remove('alpha-exit-detail-highlight'), 2200);
    }

    function activateExitWatchSelection(assetCode, accountId) {
        document.querySelectorAll('.alpha-list-item-exit').forEach((item) => {
            const itemCode = String(item.getAttribute('data-exit-asset-code') || '').toUpperCase();
            const itemAccountId = String(item.getAttribute('data-exit-account-id') || '');
            const matched = itemCode === String(assetCode || '').toUpperCase()
                && (!accountId || itemAccountId === String(accountId));
            item.classList.toggle('is-selected', matched);
        });
    }

    async function openDashboardExitDetail(link) {
        const target = getExitDetailTarget();
        const panel = getExitDetailPanel();
        if (!target || !panel || !link) {
            return false;
        }

        const href = link.getAttribute('href');
        if (!href) {
            return false;
        }

        const targetUrl = new URL(href, window.location.origin);
        const currentUrl = new URL(window.location.href);
        const assetCode = targetUrl.searchParams.get('exit_asset_code') || link.getAttribute('data-exit-asset-code') || '';
        const accountId = targetUrl.searchParams.get('exit_account_id') || link.getAttribute('data-exit-account-id') || '';
        const alphaScope = targetUrl.searchParams.get('alpha_scope') || currentUrl.searchParams.get('alpha_scope') || 'portfolio';
        const portfolioId = targetUrl.searchParams.get('portfolio_id') || currentUrl.searchParams.get('portfolio_id') || '';
        const poolMode = document.getElementById('alphaPoolModeSelect')?.value || currentUrl.searchParams.get('pool_mode') || '';

        if (!assetCode) {
            window.location.href = href;
            return true;
        }

        const apiUrl = new URL('/api/dashboard/alpha/exit-panel/', window.location.origin);
        apiUrl.searchParams.set('asset_code', assetCode);
        if (accountId) {
            apiUrl.searchParams.set('account_id', accountId);
        }
        apiUrl.searchParams.set('alpha_scope', alphaScope);
        apiUrl.searchParams.set('top_n', '10');
        if (portfolioId) {
            apiUrl.searchParams.set('portfolio_id', portfolioId);
        }
        if (poolMode && alphaScope !== 'general') {
            apiUrl.searchParams.set('pool_mode', poolMode);
        }

        panel.innerHTML = '<div class="app-loading-state app-loading-state--compact"><div class="app-spinner" aria-hidden="true"></div><p class="app-loading-text">定位退出详情...</p></div>';

        try {
            const response = await fetch(apiUrl.toString(), {
                headers: {
                    'HX-Request': 'true',
                    'X-CSRFToken': window.csrfToken || '',
                },
            });
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}`);
            }

            panel.innerHTML = await response.text();
            currentUrl.searchParams.set('alpha_scope', alphaScope);
            if (portfolioId) {
                currentUrl.searchParams.set('portfolio_id', portfolioId);
            } else {
                currentUrl.searchParams.delete('portfolio_id');
            }
            if (poolMode && alphaScope !== 'general') {
                currentUrl.searchParams.set('pool_mode', poolMode);
            }
            currentUrl.searchParams.set('exit_asset_code', assetCode);
            if (accountId) {
                currentUrl.searchParams.set('exit_account_id', accountId);
            } else {
                currentUrl.searchParams.delete('exit_account_id');
            }
            currentUrl.hash = 'alpha-exit-detail';
            window.history.replaceState({}, '', currentUrl.toString());
            activateExitWatchSelection(assetCode, accountId);
            showExitDetailHint(assetCode);
            highlightExitDetailPanel();
            return true;
        } catch (error) {
            console.error('Failed to open dashboard exit detail inline:', error);
            window.location.href = href;
            return true;
        }
    }

    window.openDashboardExitDetail = openDashboardExitDetail;

    document.addEventListener('click', (event) => {
        const link = event.target.closest('[data-dashboard-exit-detail-link="true"]');
        if (!link) {
            return;
        }
        event.preventDefault();
        void openDashboardExitDetail(link);
    });

    const params = new URLSearchParams(window.location.search);
    const initialAssetCode = params.get('exit_asset_code');
    if (!getExitDetailTarget() || !initialAssetCode) {
        return;
    }

    const initialAccountId = params.get('exit_account_id') || '';
    showExitDetailHint(initialAssetCode);
    activateExitWatchSelection(initialAssetCode, initialAccountId);
    if (document.readyState === 'complete') {
        window.setTimeout(highlightExitDetailPanel, 120);
        return;
    }

    window.addEventListener('load', () => window.setTimeout(highlightExitDetailPanel, 120), { once: true });
})();
</script>
{% endblock %}
