{% extends 'core/mobile/base_mobile.html' %}
{% block content %}
<div class="glass-card p-2 mb-2">
    <div class="input-group input-group-sm">
        <span class="input-group-text bg-dark border-secondary"><i class="bi bi-search text-secondary"></i></span>
        <input type="text" id="market-search" class="form-control bg-dark text-white border-secondary" placeholder="搜索币种" onkeyup="filterMarkets()">
    </div>
</div>

<div class="glass-card p-0">
    <div class="d-flex justify-content-between p-2 text-secondary x-small border-bottom border-secondary">
        <span style="width: 40%;">名称</span>
        <span style="width: 30%;" class="text-end">最新价</span>
        <span style="width: 30%;" class="text-end">24h 涨跌</span>
    </div>
    <div id="market-list">
        <!-- JS populated -->
    </div>
</div>

<style>
    .market-row { display: flex; justify-content: space-between; align-items: center; padding: 12px 8px; border-bottom: 1px solid #2b3139; }
</style>
{% endblock %}

{% block scripts %}
<script>
    let allMarkets = [];
    async function getMarkets() {
        try {
            const r = await fetch('/api/market_data/');
            allMarkets = await r.json();
            renderMarkets();
        } catch(e) {}
    }

    function renderMarkets(filter = '') {
        const list = document.getElementById('market-list');
        list.innerHTML = '';
        allMarkets.forEach(c => {
            if (filter && !c.symbol.toLowerCase().includes(filter.toLowerCase())) return;
            const base = c.symbol.replace('USDT', '');
            list.innerHTML += `
                <div class="market-row" onclick="location.href='{% url 'core:trade' 'spot' %}?symbol=${c.symbol}'">
                    <div style="width: 40%;">
                        <div class="fw-bold">${base}<span class="text-secondary x-small">/USDT</span></div>
                    </div>
                    <div style="width: 30%;" class="text-end fw-bold">${c.price}</div>
                    <div style="width: 30%;" class="text-end">
                        <span class="badge ${c.change>=0?'bg-success':'bg-danger'} py-1" style="min-width: 60px;">${c.change>=0?'+':''}${c.change}%</span>
                    </div>
                </div>`;
        });
    }

    function filterMarkets() {
        renderMarkets(document.getElementById('market-search').value);
    }

    getMarkets();
    setInterval(getMarkets, 3000);
</script>
{% endblock %}