/**
 * Trading Terminal JavaScript
 * OpenClaw Trading System
 */

// Global state
let currentSymbol = 'BTC/USDT';
let currentSide = 'buy';
let currentOrderType = 'limit';
let isPaperTrading = true;
let priceChart = null;
let lastPrice = 0;

// Initialize
document.addEventListener('DOMContentLoaded', () => {
    initChart();
    loadTradingMode();
    loadMarketData();
    loadAccountInfo();
    loadOrders();
    loadPositions();

    // Setup WebSocket for real-time data
    initWebSocket();

    // Auto refresh
    setInterval(() => {
        loadAccountInfo();
        loadOrders();
        loadPositions();
    }, 5000);

    // Input listeners
    document.getElementById('orderPrice').addEventListener('input', calculateTotal);
    document.getElementById('orderAmount').addEventListener('input', calculateTotal);
});

// Chart.js initialization
function initChart() {
    const ctx = document.getElementById('priceChart').getContext('2d');

    priceChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: '价格',
                data: [],
                borderColor: '#00d4aa',
                backgroundColor: 'rgba(0, 212, 170, 0.1)',
                borderWidth: 2,
                fill: true,
                tension: 0.4,
                pointRadius: 0,
                pointHoverRadius: 4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                intersect: false,
                mode: 'index'
            },
            plugins: {
                legend: { display: false },
                tooltip: {
                    backgroundColor: '#1a2332',
                    titleColor: '#e6e6e6',
                    bodyColor: '#e6e6e6',
                    borderColor: '#2d3a4a',
                    borderWidth: 1
                }
            },
            scales: {
                x: {
                    grid: { color: '#2d3a4a', drawBorder: false },
                    ticks: { color: '#8b9aad' }
                },
                y: {
                    grid: { color: '#2d3a4a', drawBorder: false },
                    ticks: { color: '#8b9aad' }
                }
            }
        }
    });
}

// WebSocket for real-time market data
let ws = null;
function initWebSocket() {
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = `${protocol}//${window.location.host}/ws/market`;

    ws = new WebSocket(wsUrl);

    ws.onopen = () => {
        console.log('WebSocket connected');
        ws.send(JSON.stringify({
            action: 'subscribe',
            symbol: currentSymbol
        }));
    };

    ws.onmessage = (event) => {
        const data = JSON.parse(event.data);
        handleWebSocketData(data);
    };

    ws.onclose = () => {
        console.log('WebSocket disconnected, retrying...');
        setTimeout(initWebSocket, 3000);
    };

    ws.onerror = (error) => {
        console.error('WebSocket error:', error);
    };
}

function handleWebSocketData(data) {
    if (data.type === 'ticker') {
        updatePriceDisplay(data.price, data.change24h);
        lastPrice = data.price;
    } else if (data.type === 'orderbook') {
        updateOrderbook(data.asks, data.bids);
    } else if (data.type === 'klines') {
        updateChart(data.candles);
    }
}

// Trading mode toggle
function toggleTradingMode() {
    const newMode = !isPaperTrading;
    fetch('/api/trading/mode', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ mode: newMode ? 'paper' : 'live' })
    })
    .then(r => r.json())
    .then(result => {
        if (result.status === 'success') {
            isPaperTrading = newMode;
            updateModeUI();
            showNotification(isPaperTrading ? '已切换到模拟交易模式' : '已切换到实盘交易模式',
                           isPaperTrading ? 'success' : 'error');
            loadAccountInfo();
        }
    });
}

function loadTradingMode() {
    fetch('/api/trading/mode')
        .then(r => r.json())
        .then(result => {
            if (result.status === 'success') {
                isPaperTrading = result.mode === 'paper';
                updateModeUI();
            }
        });
}

function updateModeUI() {
    const switchEl = document.getElementById('modeSwitch');
    const textEl = document.getElementById('modeText');

    if (isPaperTrading) {
        switchEl.classList.remove('active');
        textEl.textContent = '模拟交易';
        textEl.className = 'mode-text paper';
    } else {
        switchEl.classList.add('active');
        textEl.textContent = '实盘交易';
        textEl.className = 'mode-text live';
    }
}

// Price display
function updatePriceDisplay(price, change24h) {
    const priceEl = document.getElementById('currentPrice');
    const changeEl = document.getElementById('priceChange');

    priceEl.textContent = formatCurrency(price);

    if (change24h !== undefined) {
        const sign = change24h >= 0 ? '+' : '';
        changeEl.textContent = `${sign}${change24h.toFixed(2)}%`;
        changeEl.className = 'price-change ' + (change24h >= 0 ? 'up' : 'down');
    }
}

// Orderbook
function updateOrderbook(asks, bids) {
    const asksContainer = document.getElementById('asksList');
    const bidsContainer = document.getElementById('bidsList');

    const topAsks = asks.slice(0, 5);
    const topBids = bids.slice(0, 5);

    asksContainer.innerHTML = topAsks.map(([price, amount]) => createOrderbookRow(price, amount, 'ask')).join('');
    bidsContainer.innerHTML = topBids.map(([price, amount]) => createOrderbookRow(price, amount, 'bid')).join('');
}

function createOrderbookRow(price, amount, side) {
    const depthPercent = Math.min((amount / 10) * 100, 100);
    return `
        <div class="orderbook-row ${side}" onclick="fillPrice(${price})">
            <div class="orderbook-depth ${side}" style="width: ${depthPercent}%"></div>
            <span class="price">${parseFloat(price).toFixed(2)}</span>
            <span>${parseFloat(amount).toFixed(4)}</span>
        </div>
    `;
}

function fillPrice(price) {
    if (currentOrderType === 'limit') {
        document.getElementById('orderPrice').value = price.toFixed(2);
        calculateTotal();
    }
}

// Chart update
function updateChart(candles) {
    if (!candles || candles.length === 0) return;

    const labels = candles.map(c => new Date(c.timestamp).toLocaleTimeString('zh-CN'));
    const prices = candles.map(c => c.close);

    priceChart.data.labels = labels;
    priceChart.data.datasets[0].data = prices;
    priceChart.update('none');
}

// Market data
function loadMarketData() {
    fetch(`/api/market/ticker?symbol=${currentSymbol}`)
        .then(r => r.json())
        .then(result => {
            if (result.status === 'success') {
                updatePriceDisplay(result.data.price, result.data.change24h);
                lastPrice = result.data.price;
            }
        });

    fetch(`/api/market/orderbook?symbol=${currentSymbol}`)
        .then(r => r.json())
        .then(result => {
            if (result.status === 'success') {
                updateOrderbook(result.data.asks, result.data.bids);
            }
        });

    fetch(`/api/market/klines?symbol=${currentSymbol}&timeframe=15m`)
        .then(r => r.json())
        .then(result => {
            if (result.status === 'success') {
                updateChart(result.data);
            }
        });
}

// Account info
function loadAccountInfo() {
    fetch('/api/account/balance')
        .then(r => r.json())
        .then(result => {
            if (result.status === 'success') {
                document.getElementById('availableBalance').textContent = formatCurrency(result.data.available);
                document.getElementById('positionValue').textContent = formatCurrency(result.data.position_value);
                document.getElementById('unrealizedPnl').textContent = formatSignedCurrency(result.data.unrealized_pnl);
                document.getElementById('unrealizedPnl').className = 'info-value ' + (result.data.unrealized_pnl >= 0 ? 'pnl-positive' : 'pnl-negative');
                document.getElementById('totalEquity').textContent = formatCurrency(result.data.total_equity);
            }
        });
}

// Orders
function loadOrders() {
    fetch('/api/orders?status=open')
        .then(r => r.json())
        .then(result => {
            const tbody = document.getElementById('ordersTableBody');
            if (result.status === 'success' && result.orders.length > 0) {
                tbody.innerHTML = result.orders.map(o => `
                    <tr>
                        <td>${formatTime(o.created_at)}</td>
                        <td><strong>${o.symbol}</strong></td>
                        <td class="side-${o.side}">${o.side === 'buy' ? '买入' : '卖出'}</td>
                        <td>${o.order_type === 'limit' ? '限价' : '市价'}</td>
                        <td>${o.price ? formatCurrency(o.price) : '市价'}</td>
                        <td>${o.amount.toFixed(4)}</td>
                        <td>${o.filled_amount.toFixed(4)}</td>
                        <td>${getStatusBadge(o.status)}</td>
                        <td>
                            ${o.status === 'open' || o.status === 'partially_filled'
                                ? `<button class="btn-small btn-cancel" onclick="cancelOrder('${o.id}')">撤销</button>`
                                : '-'
                            }
                        </td>
                    </tr>
                `).join('');
            } else {
                tbody.innerHTML = '<tr><td colspan="9" style="text-align: center; color: #8b9aad; padding: 30px;">暂无订单</td></tr>';
            }
        });
}

function cancelOrder(orderId) {
    if (!confirm('确定要撤销此订单吗？')) return;

    fetch(`/api/orders/${orderId}`, { method: 'DELETE' })
        .then(r => r.json())
        .then(result => {
            if (result.status === 'success') {
                showNotification('订单已撤销', 'success');
                loadOrders();
                loadAccountInfo();
            } else {
                showNotification(result.message || '撤销失败', 'error');
            }
        });
}

// Positions
function loadPositions() {
    fetch('/api/positions')
        .then(r => r.json())
        .then(result => {
            const tbody = document.getElementById('positionsTableBody');
            if (result.status === 'success' && result.positions.length > 0) {
                tbody.innerHTML = result.positions.map(p => `
                    <tr>
                        <td><strong>${p.symbol}</strong></td>
                        <td class="side-${p.side}">${p.side === 'long' ? '做多' : '做空'}</td>
                        <td>${p.amount.toFixed(4)}</td>
                        <td>${formatCurrency(p.entry_price)}</td>
                        <td>${formatCurrency(p.mark_price)}</td>
                        <td class="${p.unrealized_pnl >= 0 ? 'pnl-positive' : 'pnl-negative'}">
                            ${p.unrealized_pnl >= 0 ? '+' : ''}${formatCurrency(p.unrealized_pnl)}
                        </td>
                        <td>
                            <button class="btn-small btn-cancel" onclick="closePosition('${p.symbol}')">平仓</button>
                        </td>
                    </tr>
                `).join('');
            } else {
                tbody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: #8b9aad; padding: 30px;">暂无持仓</td></tr>';
            }
        });
}

function closePosition(symbol) {
    if (!confirm(`确定要平仓 ${symbol} 吗？`)) return;

    fetch('/api/positions/close', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ symbol })
    })
    .then(r => r.json())
    .then(result => {
        if (result.status === 'success') {
            showNotification('平仓成功', 'success');
            loadPositions();
            loadAccountInfo();
        } else {
            showNotification(result.message || '平仓失败', 'error');
        }
    });
}

// Order submission
function setOrderType(type) {
    currentOrderType = type;
    document.querySelectorAll('.order-type-tabs .tab-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    event.target.classList.add('active');

    const priceInput = document.getElementById('orderPrice');
    if (type === 'market') {
        priceInput.value = '市价';
        priceInput.disabled = true;
    } else {
        priceInput.value = lastPrice ? lastPrice.toFixed(2) : '';
        priceInput.disabled = false;
    }
    calculateTotal();
}

function setSide(side) {
    currentSide = side;
    document.querySelectorAll('.side-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    event.target.classList.add('active');

    const submitBtn = document.getElementById('submitBtn');
    submitBtn.textContent = (side === 'buy' ? '买入 ' : '卖出 ') + currentSymbol.split('/')[0];
    submitBtn.className = 'btn-submit ' + side;
}

function calculateTotal() {
    const price = currentOrderType === 'market' ? lastPrice : parseFloat(document.getElementById('orderPrice').value) || 0;
    const amount = parseFloat(document.getElementById('orderAmount').value) || 0;
    const total = price * amount;
    document.getElementById('orderTotal').value = total > 0 ? formatCurrency(total) : '-- USDT';
}

function submitOrder() {
    const price = currentOrderType === 'market' ? null : parseFloat(document.getElementById('orderPrice').value);
    const amount = parseFloat(document.getElementById('orderAmount').value);

    if (!amount || amount <= 0) {
        showNotification('请输入有效的数量', 'error');
        return;
    }

    if (currentOrderType === 'limit' && (!price || price <= 0)) {
        showNotification('请输入有效的价格', 'error');
        return;
    }

    const data = {
        symbol: currentSymbol,
        side: currentSide,
        order_type: currentOrderType,
        amount: amount,
        price: price
    };

    fetch('/api/orders', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    })
    .then(r => r.json())
    .then(result => {
        if (result.status === 'success') {
            showNotification('订单提交成功', 'success');
            document.getElementById('orderAmount').value = '';
            document.getElementById('orderTotal').value = '-- USDT';
            loadOrders();
            loadAccountInfo();
        } else {
            showNotification(result.message || '订单提交失败', 'error');
        }
    });
}

// Symbol change
function changeSymbol() {
    currentSymbol = document.getElementById('symbolSelect').value;
    if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({
            action: 'subscribe',
            symbol: currentSymbol
        }));
    }
    loadMarketData();
}

// Tab switching
function switchTab(tab) {
    document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
    document.querySelectorAll('.tab-content').forEach(t => t.classList.remove('active'));

    event.target.classList.add('active');
    document.getElementById(tab + 'Tab').classList.add('active');

    if (tab === 'orders') loadOrders();
    if (tab === 'positions') loadPositions();
    if (tab === 'history') loadHistory();
}

function loadHistory() {
    fetch('/api/orders?status=filled')
        .then(r => r.json())
        .then(result => {
            const tbody = document.getElementById('historyTableBody');
            if (result.status === 'success' && result.orders.length > 0) {
                tbody.innerHTML = result.orders.map(o => `
                    <tr>
                        <td>${formatTime(o.updated_at || o.created_at)}</td>
                        <td><strong>${o.symbol}</strong></td>
                        <td class="side-${o.side}">${o.side === 'buy' ? '买入' : '卖出'}</td>
                        <td>${formatCurrency(o.avg_price || o.price)}</td>
                        <td>${o.filled_amount.toFixed(4)}</td>
                        <td>${formatCurrency(o.fee || 0)}</td>
                        <td>${o.realized_pnl ? formatSignedCurrency(o.realized_pnl) : '-'}</td>
                    </tr>
                `).join('');
            } else {
                tbody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: #8b9aad; padding: 30px;">暂无成交</td></tr>';
            }
        });
}

// Utilities
function formatCurrency(value) {
    if (value === undefined || value === null) return '--';
    return '$' + Number(value).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

function formatSignedCurrency(value) {
    if (value === undefined || value === null) return '--';
    const sign = value >= 0 ? '+' : '';
    return sign + formatCurrency(value);
}

function formatTime(timestamp) {
    if (!timestamp) return '--';
    return new Date(timestamp).toLocaleString('zh-CN', {
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

function getStatusBadge(status) {
    const badges = {
        'open': '<span class="badge badge-pending">挂单中</span>',
        'partially_filled': '<span class="badge badge-pending">部分成交</span>',
        'filled': '<span class="badge badge-filled">已成交</span>',
        'cancelled': '<span class="badge badge-cancelled">已取消</span>'
    };
    return badges[status] || `<span class="badge">${status}</span>`;
}

function showNotification(message, type) {
    const n = document.createElement('div');
    n.className = `notification ${type}`;
    n.textContent = message;
    document.body.appendChild(n);
    setTimeout(() => n.remove(), 3000);
}
