{% extends "base.html" %}
{% load static i18n humanize %}

{% block extra_head %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.4/dist/chart.umd.min.js"></script>
{% endblock %}

{% block title %}Invest Dashboard{% endblock %}

{% block content %}
<div class="mb-2">
    <p class="text-xs font-semibold tracking-widest text-stone-500 uppercase">{{ fy_label }} Snapshot</p>
</div>

<!-- ── Top metric cards ──────────────────────────────────────── -->
<div class="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-3">
    <div class="bg-white rounded-lg p-5 shadow-sm">
        <p class="text-xs font-semibold tracking-widest text-stone-400 uppercase mb-1">Total Value</p>
        {% if overview.this_week_total is not None %}
            <p class="text-3xl font-bold text-stone-900 tabular-nums">${{ overview.this_week_total|floatformat:0|intcomma }}</p>
        {% else %}
            <p class="text-3xl font-bold text-stone-400">—</p>
        {% endif %}
        <p class="text-sm text-stone-400 mt-1">Across {{ overview.portfolio_count }} portfolio{{ overview.portfolio_count|pluralize }}</p>
        {% if aud_total and aud_total.total_aud %}
        <p class="text-sm font-semibold text-stone-600 mt-1 tabular-nums">≈ A${{ aud_total.total_aud|floatformat:0|intcomma }}</p>
        {% endif %}
    </div>

    <div class="bg-white rounded-lg p-5 shadow-sm">
        <p class="text-xs font-semibold tracking-widest text-stone-400 uppercase mb-1">Net Contributions</p>
        <p class="text-3xl font-bold text-stone-900 tabular-nums">${{ net_contributions|floatformat:0|intcomma }}</p>
        <p class="text-sm text-stone-400 mt-1">External deposits minus withdrawals</p>
    </div>

    <div class="bg-white rounded-lg p-5 shadow-sm">
        <p class="text-xs font-semibold tracking-widest text-stone-400 uppercase mb-1">Investment Gain</p>
        <p class="text-3xl font-bold tabular-nums {% if performance.cash_adjusted_gain >= 0 %}text-green-800{% else %}text-red-700{% endif %}">
            {% if performance.cash_adjusted_gain >= 0 %}+{% endif %}${{ performance.cash_adjusted_gain|floatformat:0|intcomma }}
        </p>
        <p class="text-sm text-stone-400 mt-1">Cash-flow adjusted</p>
    </div>

    <div class="bg-white rounded-lg p-5 shadow-sm">
        <p class="text-xs font-semibold tracking-widest text-stone-400 uppercase mb-1">Top 5 Concentration</p>
        <p class="text-3xl font-bold tabular-nums {% if risk.concentration_level == 'HIGH' %}text-red-700{% elif risk.concentration_level == 'MEDIUM' %}text-amber-700{% else %}text-green-800{% endif %}">
            {% widthratio risk.top_5_weight 1 100 %}%
        </p>
        <p class="text-sm text-stone-400 mt-1">Risk: {{ risk.concentration_level }}</p>
    </div>
</div>

<div class="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-3">
    <div class="bg-white rounded-lg p-5 shadow-sm">
        <p class="text-xs font-semibold tracking-widest text-stone-400 uppercase mb-1">This Week</p>
        {% if overview.week_gain is not None %}
            <p class="text-2xl font-bold tabular-nums {% if overview.week_gain >= 0 %}text-green-800{% else %}text-red-700{% endif %}">
                {% if overview.week_gain >= 0 %}+{% endif %}${{ overview.week_gain|floatformat:0|intcomma }}
            </p>
            <p class="text-sm text-stone-400 mt-1">{% if overview.week_change_pct >= 0 %}+{% endif %}{{ overview.week_change_pct|floatformat:2 }}% vs last snapshot</p>
        {% else %}
            <p class="text-2xl font-bold text-stone-400">—</p>
            <p class="text-sm text-stone-400 mt-1">No prior snapshot</p>
        {% endif %}
    </div>

    <div class="bg-white rounded-lg p-5 shadow-sm">
        <p class="text-xs font-semibold tracking-widest text-stone-400 uppercase mb-1">Money Weighted Return</p>
        {% if performance.money_weighted_return is not None %}
            <p class="text-2xl font-bold text-stone-900 tabular-nums">{% widthratio performance.money_weighted_return 1 100 %}%</p>
        {% else %}
            <p class="text-2xl font-bold text-stone-400">—</p>
        {% endif %}
        <p class="text-sm text-stone-400 mt-1">IRR based on cash flows</p>
    </div>

    <div class="bg-white rounded-lg p-5 shadow-sm">
        <p class="text-xs font-semibold tracking-widest text-stone-400 uppercase mb-1">Unrealized P&L</p>
        {% if total_pnl is not None %}
            <p class="text-2xl font-bold tabular-nums {% if total_pnl >= 0 %}text-green-800{% else %}text-red-700{% endif %}">
                {% if total_pnl >= 0 %}+{% endif %}${{ total_pnl|floatformat:0|intcomma }}
            </p>
            <p class="text-sm text-stone-400 mt-1">{% if total_pnl_pct >= 0 %}+{% endif %}{{ total_pnl_pct|floatformat:1 }}% vs cost basis</p>
        {% else %}
            <p class="text-2xl font-bold text-stone-400">—</p>
            <p class="text-sm text-stone-400 mt-1">No cost data</p>
        {% endif %}
    </div>

    <div class="bg-white rounded-lg p-5 shadow-sm">
        <p class="text-xs font-semibold tracking-widest text-stone-400 uppercase mb-1">Last Snapshot</p>
        {% if overview.this_week_date %}
            <p class="text-2xl font-bold text-stone-900">{{ overview.this_week_date|date:"M j" }}</p>
            <p class="text-sm text-stone-400 mt-1">{{ overview.this_week_date|date:"l, Y" }}</p>
        {% else %}
            <p class="text-2xl font-bold text-stone-400">—</p>
            <p class="text-sm text-stone-400 mt-1">No snapshots yet</p>
        {% endif %}
    </div>
</div>

<!-- ── Same-cashflow benchmark ───────────────────────────────── -->
<div class="bg-white rounded-lg shadow-sm p-5 mb-3">
    <p class="text-xs font-semibold tracking-widest text-stone-500 uppercase mb-4">Same-cashflow Benchmark</p>
    <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
        <div>
            <p class="text-sm text-stone-400">Actual end value</p>
            <p class="text-xl font-bold text-stone-900 tabular-nums">${{ performance.end_value|floatformat:0|intcomma }}</p>
        </div>
        {% for ticker, bench in performance.benchmarks.items %}
        <div>
            <p class="text-sm text-stone-400">Same cash flows into {{ ticker }}</p>
            <p class="text-xl font-bold text-stone-900 tabular-nums">${{ bench.end_value|floatformat:0|intcomma }}</p>
            <p class="text-xs text-stone-400">Return {% if bench.simple_return is not None %}{% widthratio bench.simple_return 1 100 %}%{% else %}—{% endif %}</p>
        </div>
        {% empty %}
        <div class="text-sm text-stone-400">Benchmark prices unavailable. The API still returns portfolio metrics.</div>
        {% endfor %}
    </div>
</div>

<!-- ── Performance chart ─────────────────────────────────────── -->
{% if chart_data_json != 'null' %}
<div class="bg-white rounded-lg shadow-sm p-5 mb-3">
    <div class="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between mb-4">
        <div>
            <p class="text-xs font-semibold tracking-widest text-stone-500 uppercase">{{ fy_label }} Performance vs Benchmarks</p>
            <p id="performanceChartHelp" class="text-xs text-stone-400 mt-1">切换涨跌幅百分比与金额两种视图。</p>
        </div>
        <div class="flex flex-wrap items-center gap-2">
            <div class="inline-flex rounded-lg border border-stone-200 bg-stone-50 p-1 text-xs font-semibold" role="group" aria-label="Chart period">
                <button type="button" class="period-btn rounded-md px-2.5 py-1.5 text-stone-500" data-period="1M">1M</button>
                <button type="button" class="period-btn rounded-md px-2.5 py-1.5 text-stone-500" data-period="3M">3M</button>
                <button type="button" class="period-btn rounded-md px-2.5 py-1.5 text-stone-500" data-period="6M">6M</button>
                <button type="button" class="period-btn rounded-md px-2.5 py-1.5 text-stone-500" data-period="YTD">YTD</button>
                <button type="button" class="period-btn rounded-md px-2.5 py-1.5 text-stone-500" data-period="1Y">1Y</button>
                <button type="button" class="period-btn rounded-md px-2.5 py-1.5 text-stone-500" data-period="ALL">ALL</button>
            </div>
            <div class="inline-flex rounded-lg border border-stone-200 bg-stone-50 p-1 text-xs font-semibold" role="group" aria-label="Chart mode">
                <button type="button" id="chartModePercent" class="chart-mode-btn rounded-md px-3 py-1.5 bg-white text-stone-900 shadow-sm" data-mode="percentage">% Growth</button>
                <button type="button" id="chartModeValue" class="chart-mode-btn rounded-md px-3 py-1.5 text-stone-500" data-mode="value">$ Value</button>
            </div>
        </div>
    </div>
    <div class="relative h-72 md:h-80">
        <canvas id="performanceChart"></canvas>
    </div>
</div>
{% endif %}

<!-- ── Risk panel ────────────────────────────────────────────── -->
<div class="bg-white rounded-lg shadow-sm p-5 mb-4">
    <p class="text-xs font-semibold tracking-widest text-stone-500 uppercase mb-4">Risk Overview</p>
    <div class="grid grid-cols-2 md:grid-cols-4 gap-3 mb-4">
        <div><p class="text-xs text-stone-400">Top 1</p><p class="font-bold tabular-nums">{% widthratio risk.top_1_weight 1 100 %}%</p></div>
        <div><p class="text-xs text-stone-400">Top 3</p><p class="font-bold tabular-nums">{% widthratio risk.top_3_weight 1 100 %}%</p></div>
        <div><p class="text-xs text-stone-400">Semiconductors</p><p class="font-bold tabular-nums">{% widthratio risk.theme_exposure.semiconductors 1 100 %}%</p></div>
        <div><p class="text-xs text-stone-400">AI / Cloud</p><p class="font-bold tabular-nums">{% widthratio risk.theme_exposure.ai_cloud 1 100 %}%</p></div>
    </div>
    <div class="overflow-x-auto">
        <table class="w-full text-sm">
            <thead>
                <tr class="text-xs font-semibold tracking-widest text-stone-400 uppercase border-b border-stone-100">
                    <th class="py-2 text-left">Ticker</th>
                    <th class="py-2 text-right">Value</th>
                    <th class="py-2 text-right">Weight</th>
                    <th class="py-2 text-left">Accounts</th>
                </tr>
            </thead>
            <tbody>
                {% for position in risk.top_positions|slice:":5" %}
                <tr class="border-b border-stone-50">
                    <td class="py-2 font-medium"><a href="{% url 'invest-stock-detail' position.stock_code %}" class="text-blue-700 hover:underline">{{ position.stock_code }}</a></td>
                    <td class="py-2 text-right tabular-nums">${{ position.current_value|floatformat:0|intcomma }}</td>
                    <td class="py-2 text-right tabular-nums">{% widthratio position.weight 1 100 %}%</td>
                    <td class="py-2 text-stone-500">{{ position.portfolio_names|join:", " }}</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
</div>

<p class="text-xs text-stone-400 text-center mt-2 mb-6">Snapshots captured every Saturday 08:00 · Prices are best-effort market data · Cost basis estimated from trade-date close when no price was recorded</p>

<!-- ── Live holdings ─────────────────────────────────────────── -->
{% if all_holdings %}
<div class="space-y-4">
    {% for group in all_holdings %}
    <div class="bg-white rounded-lg shadow-sm overflow-hidden">
        <div class="px-6 py-4 flex items-center justify-between border-b border-stone-100">
            <div>
                <p class="font-semibold text-stone-900 text-sm">{{ group.portfolio.name }}</p>
                <p class="text-xs text-stone-400 mt-0.5">{{ group.position_count }} position{{ group.position_count|pluralize }}{% if overview.this_week_date %} · Snapshot {{ overview.this_week_date|date:"j M Y" }}{% endif %}</p>
            </div>
            <div class="text-right">
                <p class="font-bold text-stone-900 text-sm tabular-nums">{% if group.this_week_value is not None %}${{ group.this_week_value|floatformat:0|intcomma }}{% else %}<span class="text-stone-300">—</span>{% endif %}</p>
                {% if group.change is not None %}
                <p class="text-xs font-medium mt-0.5 tabular-nums {% if group.change >= 0 %}text-green-700{% else %}text-red-600{% endif %}">{% if group.change >= 0 %}+{% endif %}${{ group.change|floatformat:0|intcomma }} ({% if group.change_pct >= 0 %}+{% endif %}{{ group.change_pct|floatformat:1 }}%)</p>
                {% else %}
                <p class="text-xs text-stone-300 mt-0.5">No prior snapshot</p>
                {% endif %}
            </div>
        </div>
        <div class="overflow-x-auto">
        <table class="w-full text-sm">
            <thead>
                <tr class="text-xs font-semibold tracking-widest text-stone-400 uppercase border-b border-stone-100">
                    <th class="px-6 py-3 text-left">Ticker</th>
                    <th class="px-6 py-3 text-right">Qty</th>
                    <th class="px-6 py-3 text-right">Price</th>
                    <th class="px-6 py-3 text-right">Avg Cost</th>
                    <th class="px-6 py-3 text-right">P&amp;L</th>
                    <th class="px-6 py-3 text-right">Mkt Value</th>
                </tr>
            </thead>
            <tbody>
                {% for stock in group.holdings %}
                <tr class="border-b border-stone-50 hover:bg-stone-50 {{ group.colors.row }}">
                    <td class="px-6 py-3 font-medium text-stone-900"><a href="{% url 'invest-stock-detail' stock.stock_code %}" class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium {{ group.colors.badge }} hover:opacity-75">{{ stock.stock_code }}</a></td>
                    <td class="px-6 py-3 text-right text-stone-500 tabular-nums">{{ stock.quantity|floatformat:0|intcomma }}</td>
                    <td class="px-6 py-3 text-right text-stone-500 tabular-nums">{% if stock.current_price %}${{ stock.current_price|floatformat:2|intcomma }}{% else %}<span class="text-stone-300">—</span>{% endif %}</td>
                    <td class="px-6 py-3 text-right text-stone-500 tabular-nums">{% if stock.cost.avg_cost %}${{ stock.cost.avg_cost|floatformat:2|intcomma }}{% else %}<span class="text-stone-300">—</span>{% endif %}</td>
                    <td class="px-6 py-3 text-right tabular-nums {% if stock.cost.unrealized_pnl >= 0 %}text-green-700{% elif stock.cost.unrealized_pnl < 0 %}text-red-600{% else %}text-stone-300{% endif %}">{% if stock.cost.unrealized_pnl is not None %}{% if stock.cost.unrealized_pnl >= 0 %}+{% endif %}${{ stock.cost.unrealized_pnl|floatformat:0|intcomma }} ({% if stock.cost.pnl_pct >= 0 %}+{% endif %}{{ stock.cost.pnl_pct|floatformat:1 }}%){% else %}—{% endif %}</td>
                    <td class="px-6 py-3 text-right font-semibold text-stone-800 tabular-nums">{% if stock.current_value %}${{ stock.current_value|floatformat:0|intcomma }}{% else %}<span class="text-stone-300">—</span>{% endif %}</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
        </div>
    </div>
    {% endfor %}
</div>
{% endif %}

<!-- ── Investment reports ────────────────────────────────────── -->
{% if investment_posts %}
<div class="bg-white rounded-lg shadow-sm p-5 mt-4">
    <div class="flex items-center justify-between gap-3 mb-4">
        <div>
            <p class="text-xs font-semibold tracking-widest text-stone-500 uppercase">Investment Reports</p>
            <p class="text-xs text-stone-400 mt-1">AI-generated weekly reports linked by the <span class="font-semibold">invest</span> tag.</p>
        </div>
        {% if invest_tag %}
        <a href="{{ invest_tag.get_absolute_url }}" class="text-xs font-semibold text-blue-700 hover:text-blue-900">View all posts tagged invest</a>
        {% endif %}
    </div>
    <div class="divide-y divide-stone-100">
        {% for post in investment_posts %}
        <a href="{{ post.get_absolute_url }}" class="block py-3 hover:bg-stone-50 rounded-md px-2 -mx-2">
            <div class="flex items-start justify-between gap-3">
                <div>
                    <p class="text-sm font-semibold text-stone-900">{{ post.title }}</p>
                    {% if post.summary %}<p class="text-xs text-stone-500 mt-1 line-clamp-2">{{ post.summary }}</p>{% endif %}
                </div>
                <p class="shrink-0 text-xs text-stone-400">{{ post.created_at|date:"M j" }}</p>
            </div>
        </a>
        {% endfor %}
    </div>
</div>
{% endif %}

<!-- ── Transactions ──────────────────────────────────────────── -->
{% if recent_transactions or search_q %}
<div class="bg-white rounded-lg shadow-sm p-5 mt-4">
    <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between mb-4">
        <div>
            <p class="text-xs font-semibold tracking-widest text-stone-500 uppercase">Transaction History</p>
            <p class="text-xs text-stone-400 mt-0.5">AI/OCR 同步或手动录入 · 成本价缺失时按交易日收盘价估算</p>
        </div>
        <div class="flex flex-wrap items-center gap-2">
            <form method="get" class="flex items-center gap-1.5">
                <input type="text" name="q" value="{{ search_q }}" placeholder="搜索 ticker / 账户"
                       class="text-xs border border-stone-200 rounded-lg px-2.5 py-1.5 w-36 focus:outline-none focus:ring-2 focus:ring-blue-200">
                <button type="submit" class="text-xs font-semibold text-blue-700 hover:text-blue-900 px-1">搜索</button>
                {% if search_q %}<a href="{% url 'invest-dashboard' %}" class="text-xs text-stone-400 hover:text-stone-600">清除</a>{% endif %}
            </form>
            <a href="{% url 'invest-transaction-create' %}" class="text-xs font-semibold bg-blue-600 hover:bg-blue-700 text-white rounded-lg px-2.5 py-1.5">+ 交易</a>
            <a href="{% url 'invest-cashflow-create' %}" class="text-xs font-semibold border border-stone-200 text-stone-600 hover:bg-stone-50 rounded-lg px-2.5 py-1.5">+ 现金流</a>
        </div>
    </div>
    {% if recent_transactions %}
    <div class="overflow-x-auto">
        <table class="w-full text-sm">
            <thead>
                <tr class="text-xs font-semibold tracking-widest text-stone-400 uppercase border-b border-stone-100">
                    <th class="py-2 text-left">Date</th>
                    <th class="py-2 text-left">Portfolio</th>
                    <th class="py-2 text-left">Action</th>
                    <th class="py-2 text-left">Ticker</th>
                    <th class="py-2 text-right">Qty</th>
                    <th class="py-2 text-right">Price</th>
                    <th class="py-2 text-right">Fee</th>
                    <th class="py-2 text-left">Source</th>
                </tr>
            </thead>
            <tbody>
                {% for tx in recent_transactions %}
                <tr class="border-b border-stone-50">
                    <td class="py-2">{{ tx.date|date:"j M Y" }}</td>
                    <td class="py-2">{{ tx.portfolio.name }}</td>
                    <td class="py-2 {% if tx.action == 'BUY' %}text-green-700{% else %}text-red-600{% endif %} font-medium">{{ tx.action }}</td>
                    <td class="py-2 font-medium"><a href="{% url 'invest-stock-detail' tx.stock_code %}" class="text-blue-700 hover:underline">{{ tx.stock_code }}</a></td>
                    <td class="py-2 text-right tabular-nums">{{ tx.quantity|floatformat:0|intcomma }}</td>
                    <td class="py-2 text-right tabular-nums">{% if tx.price_per_share %}${{ tx.price_per_share|floatformat:2|intcomma }}{% else %}<span class="text-stone-300">~估算</span>{% endif %}</td>
                    <td class="py-2 text-right tabular-nums">{% if tx.fee %}${{ tx.fee|floatformat:2|intcomma }}{% else %}<span class="text-stone-300">—</span>{% endif %}</td>
                    <td class="py-2">
                        {% if tx.source %}
                        <span class="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium {% if tx.source|lower == 'ai' or tx.source|lower == 'ocr' %}bg-purple-100 text-purple-700{% else %}bg-stone-100 text-stone-500{% endif %}">
                            {% if tx.source|lower == 'ai' or tx.source|lower == 'ocr' %}🤖 AI{% else %}手动{% endif %}
                        </span>
                        {% if tx.confidence is not None and tx.confidence < 0.9 %}
                        <span class="ml-1 inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-amber-100 text-amber-700" title="AI 识别置信度 {{ tx.confidence|floatformat:2 }}">⚠ 低置信</span>
                        {% endif %}
                        {% endif %}
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
    {% else %}
    <div class="py-8 text-center">
        <p class="text-sm text-stone-400">没有匹配 "{{ search_q }}" 的交易</p>
    </div>
    {% endif %}
</div>
{% endif %}

{% endblock %}

{% block extra_js %}
{% if chart_data_json != 'null' %}
<script>
(function () {
    const raw = {{ chart_data_json|safe }};
    if (!raw || !raw.periods) return;
    const ctx = document.getElementById('performanceChart');
    if (!ctx) return;

    const help = document.getElementById('performanceChartHelp');
    const periods = raw.periods;
    const defaultPeriod = raw.default || 'YTD';
    let currentPeriod = periods[defaultPeriod] ? defaultPeriod : Object.keys(periods)[0];
    let currentMode = 'percentage';

    function formatCurrency(value) {
        return '$' + value.toLocaleString(undefined, { maximumFractionDigits: 0 });
    }

    function formatPercent(value) {
        const sign = value >= 0 ? '+' : '';
        return sign + value.toFixed(2) + '%';
    }

    function currentData() {
        const period = periods[currentPeriod];
        const modes = period.modes;
        const modeData = modes[currentMode] || modes.percentage;
        return { labels: period.labels, datasets: modeData.datasets, unit: modeData.unit, baseline: period.baseline_date };
    }

    function chartOptions() {
        const unit = currentData().unit;
        return {
            responsive: true,
            maintainAspectRatio: false,
            interaction: { mode: 'index', intersect: false },
            plugins: {
                legend: {
                    position: 'top',
                    align: 'start',
                    labels: { usePointStyle: true, pointStyle: 'rect', pointStyleWidth: 10, padding: 10, boxWidth: 10, font: { size: 11, weight: '600' } },
                },
                tooltip: {
                    position: 'nearest',
                    padding: 8,
                    titleFont: { size: 11 },
                    bodyFont: { size: 10 },
                    callbacks: { label: function (ctx) { const v = ctx.parsed.y; if (v === null || v === undefined) return ctx.dataset.label + ': —'; return ctx.dataset.label + ': ' + (unit === 'currency' ? formatCurrency(v) : formatPercent(v)); } },
                },
            },
            scales: {
                y: {
                    grace: '5%',
                    ticks: { maxTicksLimit: 6, callback: function (v) { return unit === 'currency' ? formatCurrency(Number(v)) : formatPercent(Number(v)); }, font: { size: 10 } },
                    grid: { color: '#f5f5f4' },
                },
                x: {
                    grid: { display: false },
                    ticks: { autoSkip: true, maxRotation: 0, maxTicksLimit: 8, font: { size: 10 } },
                },
            },
        };
    }

    const chart = new Chart(ctx, {
        type: 'line',
        data: currentData(),
        options: chartOptions(),
    });

    function render() {
        chart.data = currentData();
        chart.options = chartOptions();
        chart.update();
        if (help) {
            const baseline = currentData().baseline || '基准日';
            help.textContent = currentMode === 'value'
                ? `金额视图：组合总市值 vs SPY/QQQ 基准（自 ${baseline}）`
                : `涨跌幅视图：自 ${baseline} 以来的涨跌幅；卡片上方为现金流调整指标`;
        }
    }

    function refreshToggleButtons(buttons, activeKey) {
        buttons.forEach((button) => {
            const active = button.dataset.period === activeKey || button.dataset.mode === activeKey;
            button.classList.toggle('bg-white', active);
            button.classList.toggle('text-stone-900', active);
            button.classList.toggle('shadow-sm', active);
            button.classList.toggle('text-stone-500', !active);
        });
    }

    document.querySelectorAll('.period-btn').forEach((button) => {
        button.addEventListener('click', () => {
            if (!periods[button.dataset.period]) return;
            currentPeriod = button.dataset.period;
            refreshToggleButtons(document.querySelectorAll('.period-btn'), currentPeriod);
            render();
        });
    });

    document.querySelectorAll('.chart-mode-btn').forEach((button) => {
        button.addEventListener('click', () => {
            currentMode = button.dataset.mode;
            refreshToggleButtons(document.querySelectorAll('.chart-mode-btn'), currentMode);
            render();
        });
    });

    // 初始状态
    refreshToggleButtons(document.querySelectorAll('.period-btn'), currentPeriod);
    refreshToggleButtons(document.querySelectorAll('.chart-mode-btn'), currentMode);
    render();
})();
</script>
{% endif %}
{% endblock %}
