{% extends 'core/mobile/base_mobile.html' %}
{% load static %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-2 px-1 py-1" style="background: #161a1e;">
    <div class="dropdown">
        <button class="btn btn-sm btn-dark dropdown-toggle fs-6 fw-bold text-warning" type="button" data-bs-toggle="dropdown">
            <span id="current-symbol-display">{{ symbol }}</span>
        </button>
        <ul class="dropdown-menu dropdown-menu-dark shadow-lg" id="mobile-coin-list" style="max-height: 300px; overflow-y: auto;">
            <!-- JS populated -->
        </ul>
    </div>
    <div class="d-flex gap-1 bg-dark p-1 rounded">
        <a href="{% url 'core:trade' 'spot' %}?symbol={{ symbol }}" class="btn btn-xs {% if trade_type == 'SPOT' %}btn-warning text-dark{% else %}btn-dark text-secondary{% endif %} py-1 px-3 small fw-bold">现货</a>
        <a href="{% url 'core:trade' 'contract' %}?symbol={{ symbol }}" class="btn btn-xs {% if trade_type == 'CONTRACT' %}btn-warning text-dark{% else %}btn-dark text-secondary{% endif %} py-1 px-3 small fw-bold">合约</a>
    </div>
</div>

<div class="row g-1 mb-2">
    <!-- Market Data Column -->
    <div class="col-5">
        <div class="glass-card p-2" style="height: 100%; font-size: 11px; background: #161a1e; border: 1px solid #2b3139;">
            <div class="d-flex justify-content-between text-secondary mb-2">
                <span>价格</span><span>数量</span>
            </div>
            <div id="m-asks" class="mb-2"></div>
            <div class="text-center py-2 fw-bold text-success border-top border-bottom border-secondary my-2" id="m-current-price" style="font-size: 16px;">--</div>
            <div id="m-bids"></div>
        </div>
    </div>

    <!-- Order Form Column -->
    <div class="col-7">
        <div class="glass-card p-2" style="background: #161a1e; border: 1px solid #2b3139;">
            {% if trade_type == 'SPOT' %}
            <div class="btn-group w-100 mb-2" role="group">
                <input type="radio" class="btn-check" name="trade-side" id="buy-side" checked onchange="toggleSide('BUY')">
                <label class="btn btn-outline-success btn-sm py-1" for="buy-side">买入</label>
                <input type="radio" class="btn-check" name="trade-side" id="sell-side" onchange="toggleSide('SELL')">
                <label class="btn btn-outline-danger btn-sm py-1" for="sell-side">卖出</label>
            </div>
            <select class="form-select form-select-sm bg-dark text-white border-secondary mb-2" id="spot-mode-select" onchange="toggleModeMobile()">
                <option value="limit">限价委托</option>
                <option value="market">市价委托</option>
            </select>
            {% else %}
            <div class="d-flex gap-2 mb-2">
                <div class="dropdown w-50">
                    <button class="btn btn-sm btn-dark border-secondary w-100 text-warning fw-bold" id="lev-btn" data-bs-toggle="dropdown">20x</button>
                    <ul class="dropdown-menu dropdown-menu-dark">
                        <li><a class="dropdown-item" href="javascript:void(0)" onclick="setLev(10)">10x</a></li>
                        <li><a class="dropdown-item" href="javascript:void(0)" onclick="setLev(20)">20x</a></li>
                        <li><a class="dropdown-item" href="javascript:void(0)" onclick="setLev(50)">50x</a></li>
                        <li><a class="dropdown-item" href="javascript:void(0)" onclick="setLev(100)">100x</a></li>
                    </ul>
                </div>
                <select class="form-select form-select-sm bg-dark text-white border-secondary w-50" id="c-mode-select" onchange="toggleModeMobile()">
                    <option value="limit">限价</option>
                    <option value="market">市价</option>
                </select>
            </div>
            {% endif %}

            <div class="mb-2">
                <div class="input-group input-group-sm">
                    <span class="input-group-text bg-dark border-secondary text-secondary" style="width: 40px; font-size: 10px;">价</span>
                    <input type="text" id="m-price" class="form-control bg-transparent text-white border-secondary" placeholder="价格">
                </div>
            </div>

            <div class="mb-1">
                <div class="input-group input-group-sm">
                    <span class="input-group-text bg-dark border-secondary text-secondary" style="width: 40px; font-size: 10px;" id="m-label">数</span>
                    <input type="number" id="m-amount" class="form-control bg-transparent text-white border-secondary" placeholder="0.00" oninput="updateSliderMobile()">
                    <span class="input-group-text bg-dark border-secondary text-secondary x-small" id="m-unit">{{ base_symbol }}</span>
                </div>
            </div>

            <div class="mb-3 px-1">
                <input type="range" class="form-range custom-range" id="m-slider" min="0" max="100" step="1" value="0" oninput="applySliderMobile()">
                <div class="d-flex justify-content-between x-small text-secondary" style="font-size: 9px;">
                    <span>0%</span><span>25%</span><span>50%</span><span>75%</span><span>100%</span>
                </div>
            </div>

            <div class="x-small mb-2 d-flex justify-content-between text-secondary" style="font-size: 10px;">
                <span>可用:</span>
                <span id="m-available" class="text-white">--</span>
            </div>

            {% if trade_type == 'CONTRACT' %}
            <div class="row g-1">
                <div class="col-6"><button class="btn btn-success btn-sm w-100 fw-bold" onclick="submitOrderMobile('BUY')">开多</button></div>
                <div class="col-6"><button class="btn btn-danger btn-sm w-100 fw-bold" onclick="submitOrderMobile('SELL')">开空</button></div>
            </div>
            {% else %}
            <button class="btn btn-success w-100 fw-bold btn-sm" id="m-submit-btn" onclick="submitOrderMobile(side)">买入</button>
            {% endif %}
        </div>
    </div>
</div>

<!-- Chart Tab -->
<div class="glass-card p-1 mb-2" style="background: #161a1e; border: 1px solid #2b3139;">
    <div id="tradingview_widget" style="height: 250px;"></div>
</div>

<!-- Positions List -->
<div class="glass-card p-2" style="background: #161a1e; border: 1px solid #2b3139;">
    <div class="fw-bold mb-2 small border-bottom border-secondary pb-1 d-flex justify-content-between">
        <span>当前持仓/挂单</span>
        <span class="text-warning x-small" style="font-weight: normal; cursor: pointer;" onclick="location.reload()"><i class="bi bi-arrow-clockwise"></i> 刷新</span>
    </div>
    <div id="m-positions-list">
        {% if trade_type == 'CONTRACT' %}
            {% for p in account.positions.all %}
                {% if p.is_active %}
                <div class="mb-2 p-2 bg-dark rounded border-start border-3 {% if p.side == 'LONG' %}border-success{% else %}border-danger{% endif %}" style="border: 1px solid #2b3139;">
                    <div class="d-flex justify-content-between x-small mb-1">
                        <span class="fw-bold text-white">{{ p.symbol }} <span class="badge bg-secondary">{{ p.leverage }}x</span> <span class="{% if p.side == 'LONG' %}text-success{% else %}text-danger{% endif %}">{% if p.side == 'LONG' %}多{% else %}空{% endif %}</span></span>
                        <span class="upl-val fw-bold" data-entry="{{ p.entry_price }}" data-side="{{ p.side }}" data-lots="{{ p.lots }}">--</span>
                    </div>
                    <div class="d-flex justify-content-between x-small text-secondary" style="font-size: 10px;">
                        <span>手数: {{ p.lots }}</span>
                        <span>开仓价: {{ p.entry_price|floatformat:2 }}</span>
                    </div>
                    <div class="d-flex justify-content-between x-small text-secondary mb-1" style="font-size: 10px;">
                        <span>保证金: {{ p.margin|floatformat:2 }}</span>
                        <span class="current-p-val" data-symbol="{{ p.symbol }}">当前: --</span>
                    </div>
                    <button class="btn btn-outline-danger btn-xs py-0 w-100 mt-1" style="font-size: 11px;" onclick="closePos({{ p.id }})">市价平仓</button>
                </div>
                {% endif %}
            {% endfor %}
        {% endif %}
        {% for o in account.orders.all %}
            {% if o.status == 'PENDING' %}
            <div class="mb-2 p-2 bg-dark rounded border-start border-3 border-warning" style="border: 1px solid #2b3139;">
                <div class="d-flex justify-content-between x-small">
                    <span class="text-white">{{ o.symbol }} ({{ o.get_trade_type_display }}) <span class="{% if o.side == 'BUY' %}text-success{% else %}text-danger{% endif %}">{{ o.get_side_display }}</span></span>
                    <span class="text-warning">委托中</span>
                </div>
                <div class="d-flex justify-content-between x-small text-secondary mt-1" style="font-size: 10px;">
                    <span>价格: {{ o.price|default:"市价" }}</span>
                    <span>数量: {{ o.amount }}</span>
                </div>
                <button class="btn btn-outline-secondary btn-xs py-0 w-100 mt-1" style="font-size: 11px;">撤单</button>
            </div>
            {% endif %}
        {% endfor %}
    </div>
</div>

<style>
    .btn-xs { padding: 1px 5px; font-size: 10px; }
    .order-row { display: flex; justify-content: space-between; margin-bottom: 2px; height: 16px; overflow: hidden; position: relative; }
    .order-row span { position: relative; z-index: 1; }
    .ask-bg { position: absolute; right: 0; top: 0; bottom: 0; background: rgba(246, 70, 93, 0.1); }
    .bid-bg { position: absolute; right: 0; top: 0; bottom: 0; background: rgba(14, 203, 129, 0.1); }
    .custom-range::-webkit-slider-thumb { background: #f0b90b; }
</style>
{% endblock %}

{% block scripts %}
<script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script>
<script>
    const symbol = '{{ symbol }}';
    const tradeType = '{{ trade_type }}';
    const baseAsset = '{{ base_symbol }}';
    const balance = parseFloat("{{ account.balance|default:0 }}");
    const assetBalance = parseFloat("{{ base_asset_balance|default:0 }}");
    let currentPrice = 0;
    let leverage = 20;
    let side = 'BUY';

    function initTV() {
        new TradingView.widget({
            "width": "100%", "height": "100%", "symbol": "BINANCE:" + symbol,
            "interval": "15", "theme": "dark", "style": "1", "locale": "zh_CN",
            "container_id": "tradingview_widget", "hide_side_toolbar": true, "save_image": false
        });
    }

    async function getMarkets() {
        try {
            const r = await fetch('/api/market_data/');
            const data = await r.json();
            const list = document.getElementById('mobile-coin-list');
            list.innerHTML = '';
            data.forEach(c => {
                const b = c.symbol.replace('USDT', '');
                const iconUrl = `https://static.okx.com/cdn/oksupport/asset/currency/icon/${b.toLowerCase()}.png`;
                list.innerHTML += `<li><a class="dropdown-item d-flex justify-content-between" href="?symbol=${c.symbol}"><span><img src="${iconUrl}" style="width:16px;margin-right:5px;" onerror="this.src='https://static.okx.com/cdn/oksupport/asset/currency/icon/generic.png'">${b}</span><span class="${c.change>=0?'text-success':'text-danger'}">${c.price}</span></a></li>`;
            });
        } catch(e) {}
    }

    function toggleSide(s) {
        side = s;
        const btn = document.getElementById('m-submit-btn');
        if (btn) {
            if (s === 'BUY') {
                btn.className = 'btn btn-success w-100 fw-bold btn-sm';
                btn.textContent = '立即买入';
            } else {
                btn.className = 'btn btn-danger w-100 fw-bold btn-sm';
                btn.textContent = '立即卖出';
            }
        }
        
        const avail = document.getElementById('m-available');
        if (tradeType === 'SPOT') {
            if (s === 'BUY') avail.textContent = balance.toFixed(2) + ' USDT';
            else avail.textContent = assetBalance.toFixed(4) + ' ' + baseAsset;
        } else {
            avail.textContent = balance.toFixed(2) + ' USDT';
        }
        toggleModeMobile();
    }

    function toggleModeMobile() {
        const mode = tradeType === 'SPOT' 
            ? document.getElementById('spot-mode-select').value 
            : document.getElementById('c-mode-select').value;
        const pInput = document.getElementById('m-price');
        const unit = document.getElementById('m-unit');
        const label = document.getElementById('m-label');

        if (mode === 'market') {
            pInput.value = currentPrice || '市价';
            pInput.disabled = true;
            pInput.style.color = '#f0b90b';
            if (tradeType === 'SPOT' && side === 'BUY') {
                label.textContent = '额';
                unit.textContent = 'USDT';
            } else {
                label.textContent = '数';
                unit.textContent = tradeType === 'SPOT' ? baseAsset : '张';
            }
        } else {
            pInput.value = '';
            pInput.disabled = false;
            pInput.style.color = 'white';
            label.textContent = '数';
            unit.textContent = tradeType === 'SPOT' ? baseAsset : '张';
        }
        applySliderMobile();
    }

    function applySliderMobile() {
        const val = document.getElementById('m-slider').value;
        const mode = tradeType === 'SPOT' 
            ? document.getElementById('spot-mode-select').value 
            : document.getElementById('c-mode-select').value;

        const amountInput = document.getElementById('m-amount');

        if (tradeType === 'SPOT') {
            if (side === 'BUY') {
                if (mode === 'market') {
                    amountInput.value = (balance * (val / 100)).toFixed(2);
                } else {
                    const price = parseFloat(document.getElementById('m-price').value) || currentPrice;
                    if (price > 0) amountInput.value = (balance * (val / 100) / price).toFixed(4);
                    else amountInput.value = 0;
                }
            } else {
                amountInput.value = (assetBalance * (val / 100)).toFixed(4);
            }
        } else {
            const maxLots = (balance * leverage) / 100;
            amountInput.value = Math.floor(maxLots * (val / 100));
        }
    }

    function updateSliderMobile() {
        const val = parseFloat(document.getElementById('m-amount').value) || 0;
        const slider = document.getElementById('m-slider');
        if (tradeType === 'SPOT') {
            if (side === 'BUY') {
                const mode = document.getElementById('spot-mode-select').value;
                if (mode === 'market') {
                    if (balance > 0) slider.value = (val / balance) * 100;
                } else {
                    const price = parseFloat(document.getElementById('m-price').value) || currentPrice;
                    if (balance > 0 && price > 0) slider.value = (val * price / balance) * 100;
                }
            } else {
                if (assetBalance > 0) slider.value = (val / assetBalance) * 100;
            }
        } else {
            const maxLots = (balance * leverage) / 100;
            if (maxLots > 0) slider.value = (val / maxLots) * 100;
        }
    }

    function setLev(l) {
        leverage = l;
        document.getElementById('lev-btn').textContent = l + 'x';
        applySliderMobile();
    }

    async function tick() {
        try {
            const r = await fetch('/api/market_data/');
            const data = await r.json();
            const d = data.find(c => c.symbol === symbol);
            if (!d) return;
            currentPrice = parseFloat(d.price);
            document.getElementById('m-current-price').textContent = currentPrice.toLocaleString();
            
            const pInput = document.getElementById('m-price');
            if (pInput && pInput.disabled) pInput.value = currentPrice;

            const askD = document.getElementById('m-asks'); const bidD = document.getElementById('m-bids');
            askD.innerHTML = ''; bidD.innerHTML = '';
            for (let i = 0; i < 5; i++) {
                const ap = (currentPrice+(5-i)*0.1).toFixed(2);
                const bp = (currentPrice-(i+1)*0.1).toFixed(2);
                askD.innerHTML = `<div class="order-row"><span class="text-danger">${ap}</span><span class="text-secondary">${(Math.random()*0.5).toFixed(3)}</span><div class="ask-bg" style="width:${Math.random()*60}%"></div></div>` + askD.innerHTML;
                bidD.innerHTML += `<div class="order-row"><span class="text-success">${bp}</span><span class="text-secondary">${(Math.random()*0.5).toFixed(3)}</span><div class="bid-bg" style="width:${Math.random()*60}%"></div></div>`;
            }

            document.querySelectorAll('.current-p-val').forEach(el => { el.textContent = '当前: ' + currentPrice.toLocaleString(); });
            document.querySelectorAll('.upl-val').forEach(el => {
                const entry = parseFloat(el.getAttribute('data-entry'));
                const sideP = el.getAttribute('data-side');
                const lots = parseFloat(el.getAttribute('data-lots'));
                let upl = sideP === 'LONG' ? (currentPrice - entry) / entry * (lots * 100) : (entry - currentPrice) / entry * (lots * 100);
                el.textContent = (upl >= 0 ? '+' : '') + upl.toFixed(2) + ' USDT';
                el.className = 'upl-val fw-bold ' + (upl >= 0 ? 'text-success' : 'text-danger');
            });
        } catch(e) {}
    }

    async function submitOrderMobile(sideParam) {
        const mode = tradeType === 'SPOT' ? document.getElementById('spot-mode-select').value : document.getElementById('c-mode-select').value;
        const price = document.getElementById('m-price').value;
        const amount = document.getElementById('m-amount').value;

        if (mode === 'limit' && (!price || isNaN(parseFloat(price)))) {
            alert('请输入有效委托价格'); return;
        }
        if (!amount || amount <= 0) {
            alert('请输入数量'); return;
        }

        try {
            const r = await fetch('{% url "core:submit_order" %}', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' },
                body: JSON.stringify({
                    symbol: symbol, side: sideParam, trade_type: tradeType, order_type: mode.toUpperCase(),
                    price: mode === 'market' ? null : price, amount: amount, leverage: leverage
                })
            });
            const res = await r.json();
            if (res.status === 'success') { alert('下单成功！'); location.reload(); }
            else { alert('失败: ' + res.message); }
        } catch(e) { alert('提交出错'); }
    }

    async function closePos(id) {
        if (confirm('确定平仓？')) {
            const r = await fetch(`/api/close_position/${id}/`, { method: 'POST', headers: { 'X-CSRFToken': '{{ csrf_token }}' } });
            const res = await r.json();
            if (res.status === 'success') location.reload();
        }
    }

    initTV(); getMarkets(); tick();
    setInterval(tick, 2000);
    toggleSide('BUY');
</script>
{% endblock %}