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

{% 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">${{ overview.this_week_total|floatformat:0 }}</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>
    </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-blue-800">${{ net_contributions|floatformat:0 }}</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 {% 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 }}
        </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 {% 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-1 lg:grid-cols-3 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 {% if overview.week_gain >= 0 %}text-green-800{% else %}text-red-700{% endif %}">
                {% if overview.week_gain >= 0 %}+{% endif %}${{ overview.week_gain|floatformat:0 }}
            </p>
            <p class="text-sm text-stone-400 mt-1">{% if overview.week_gain >= 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">{% 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">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">${{ performance.end_value|floatformat:0 }}</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">${{ bench.end_value|floatformat:0 }}</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 md:flex-row md:items-center md:justify-between mb-4">
        <div>
            <p class="text-xs font-semibold tracking-widest text-stone-500 uppercase">{{ fy_label }} Performance vs Benchmarks</p>
            <p class="text-xs text-stone-400 mt-1">Toggle between percentage return and dollar-value growth from the baseline date.</p>
        </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>
    <canvas id="performanceChart" height="90"></canvas>
    <p id="performanceChartHelp" class="text-xs text-stone-400 mt-3">Snapshot value chart; cash-flow-adjusted metrics are shown in the cards above.</p>
</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">{% widthratio risk.top_1_weight 1 100 %}%</p></div>
        <div><p class="text-xs text-stone-400">Top 3</p><p class="font-bold">{% widthratio risk.top_3_weight 1 100 %}%</p></div>
        <div><p class="text-xs text-stone-400">Semiconductors</p><p class="font-bold">{% widthratio risk.theme_exposure.semiconductors 1 100 %}%</p></div>
        <div><p class="text-xs text-stone-400">AI / Cloud</p><p class="font-bold">{% 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">Portfolio</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">{{ position.stock_code }}</td>
                    <td class="py-2 text-right">${{ position.current_value|floatformat:0 }}</td>
                    <td class="py-2 text-right">{% widthratio position.weight 1 100 %}%</td>
                    <td class="py-2 text-stone-500">{{ position.portfolio_name }}</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 · Transaction prices are optional for AI sync</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">{% if group.this_week_value is not None %}${{ group.this_week_value|floatformat:0 }}{% else %}<span class="text-stone-300">—</span>{% endif %}</p>
                {% if group.change is not None %}
                <p class="text-xs font-medium mt-0.5 {% if group.change >= 0 %}text-green-700{% else %}text-red-600{% endif %}">{% if group.change >= 0 %}+{% endif %}${{ group.change|floatformat:0 }} ({% 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>
        <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">Week Change</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"><span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium {{ group.colors.badge }}">{{ stock.stock_code }}</span></td>
                    <td class="px-6 py-3 text-right text-stone-500">{{ stock.quantity|floatformat:0 }}</td>
                    <td class="px-6 py-3 text-right text-stone-500">{% if stock.current_price %}${{ stock.current_price|floatformat:2 }}{% else %}<span class="text-stone-300">—</span>{% endif %}</td>
                    <td class="px-6 py-3 text-right {% if stock.value_change >= 0 %}text-green-700{% elif stock.value_change < 0 %}text-red-600{% else %}text-stone-300{% endif %}">{% if stock.value_change is not None %}{% if stock.value_change >= 0 %}+{% endif %}${{ stock.value_change|floatformat:0 }} ({% if stock.price_change_pct >= 0 %}+{% endif %}{{ stock.price_change_pct|floatformat:1 }}%){% else %}—{% endif %}</td>
                    <td class="px-6 py-3 text-right font-semibold text-stone-800">{% if stock.current_value %}${{ stock.current_value|floatformat:0 }}{% else %}<span class="text-stone-300">—</span>{% endif %}</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </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 %}
<div class="bg-white rounded-lg shadow-sm p-5 mt-4">
    <p class="text-xs font-semibold tracking-widest text-stone-500 uppercase mb-4">Transaction History</p>
    <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>
                </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">{{ tx.action }}</td>
                    <td class="py-2 font-medium">{{ tx.stock_code }}</td>
                    <td class="py-2 text-right">{{ tx.quantity|floatformat:0 }}</td>
                    <td class="py-2 text-right">{% if tx.price_per_share %}${{ tx.price_per_share|floatformat:2 }}{% else %}<span class="text-stone-300">optional</span>{% endif %}</td>
                    <td class="py-2 text-right">{% if tx.fee %}${{ tx.fee|floatformat:2 }}{% else %}<span class="text-stone-300">—</span>{% endif %}</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
</div>
{% endif %}

{% endblock %}

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

    const help = document.getElementById('performanceChartHelp');
    const buttons = Array.from(document.querySelectorAll('.chart-mode-btn'));
    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 chartDataFor(mode) {
        const modeData = raw.modes[mode] || raw.modes.percentage;
        return {
            labels: raw.labels,
            datasets: modeData.datasets,
        };
    }

    function chartOptionsFor(mode) {
        const unit = (raw.modes[mode] || raw.modes.percentage).unit;
        return {
            responsive: true,
            interaction: { mode: 'index', intersect: false },
            plugins: {
                legend: { position: 'top', align: 'start', labels: { usePointStyle: true, pointStyle: 'rect', pointStyleWidth: 14, padding: 20, font: { size: 12, weight: '600' } } },
                tooltip: { 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: { ticks: { callback: function (v) { return unit === 'currency' ? formatCurrency(Number(v)) : formatPercent(Number(v)); }, font: { size: 11 } }, grid: { color: '#f5f5f4' } },
                x: { grid: { display: false }, ticks: { font: { size: 11 } } },
            },
        };
    }

    const chart = new Chart(ctx, {
        type: 'line',
        data: chartDataFor(currentMode),
        options: chartOptionsFor(currentMode),
    });

    function setMode(mode) {
        currentMode = mode;
        chart.data = chartDataFor(mode);
        chart.options = chartOptionsFor(mode);
        chart.update();
        buttons.forEach((button) => {
            const active = button.dataset.mode === mode;
            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);
        });
        if (help) {
            const baseline = raw.baseline_date || 'the baseline date';
            help.textContent = mode === 'value'
                ? `Dollar mode: actual total portfolio value vs SPY/QQQ benchmark value from ${baseline}.`
                : `Percentage mode: growth/decline since ${baseline}; cash-flow-adjusted metrics are shown in the cards above.`;
        }
    }

    buttons.forEach((button) => button.addEventListener('click', () => setMode(button.dataset.mode)));
    setMode(currentMode);
})();
</script>
{% endif %}
{% endblock %}
