@extends('layouts.client')
@section('title', 'Orders')
@section('content')
<h2 style="font-size:1.1rem;font-weight:800;margin-bottom:0.35rem">Completed Trades</h2>
<p style="color:var(--client-muted);font-size:0.85rem;margin-bottom:1rem">
    Available Balance: <strong style="color:var(--client-accent)">{{ number_format(auth()->user()->balance, 2) }} {{ $currency }}</strong>
</p>
<p style="color:var(--client-muted);font-size:0.8rem;margin-bottom:1rem">Tap a trade to view receipt</p>

@forelse($trades as $trade)
@php $quote = $trade->market->quoteCurrency(); @endphp
<button type="button" class="order-card order-card--clickable" data-trade-id="{{ $trade->id }}" aria-label="View receipt for trade {{ $trade->id }}">
    <div>
        <strong>{{ $trade->market->tradePairLabel() }}</strong>
        @if($trade->market->isMetal())
        <span class="order-metal-tag">{{ $trade->market->name }}</span>
        @endif
        <p style="font-size:0.8rem;color:var(--client-muted);margin-top:0.25rem">
            Amount: {{ number_format($trade->amount, 2) }} {{ $quote }}
        </p>
    </div>
    <div style="text-align:center">
        <span class="badge-{{ $trade->direction }}">{{ strtoupper($trade->direction) }}</span>
        <p style="font-size:0.75rem;color:var(--client-muted);margin-top:0.35rem">
            Duration: {{ $trade->period->duration_seconds }}s · ID: {{ $trade->id }}
        </p>
    </div>
    <div style="text-align:right">
        <p class="order-outcome-{{ $trade->outcome }}">{{ strtoupper($trade->outcome) }}</p>
        <p style="font-size:0.7rem;color:var(--client-muted);margin-top:0.35rem">
            Ended: {{ $trade->closed_at?->format('M d, Y H:i:s') }}
        </p>
    </div>
</button>
@empty
<div class="empty-state client-card">No completed trades yet.</div>
@endforelse

@if($trades->hasPages())
<div style="margin-top:1rem">{{ $trades->links() }}</div>
@endif

<h2 style="font-size:1.1rem;font-weight:800;margin:1.5rem 0 0.75rem">Asset Trades</h2>
<p style="color:var(--client-muted);font-size:0.8rem;margin-bottom:0.75rem">Gold, silver, and other metals</p>

@forelse($metalTrades as $trade)
@php $quote = $trade->market->quoteCurrency(); @endphp
<button type="button" class="order-card order-card-metal order-card--clickable" data-trade-id="{{ $trade->id }}" aria-label="View receipt for trade {{ $trade->id }}">
    <div>
        <strong>{{ $trade->market->name }}</strong>
        <p style="font-size:0.8rem;color:var(--client-muted);margin-top:0.25rem">
            {{ $trade->market->tradePairLabel() }} · {{ number_format($trade->amount, 2) }} {{ $quote }}
        </p>
    </div>
    <div style="text-align:center">
        <span class="badge-{{ $trade->direction }}">{{ strtoupper($trade->direction) }}</span>
        <p style="font-size:0.75rem;color:var(--client-muted);margin-top:0.35rem">{{ $trade->period->duration_seconds }}s</p>
    </div>
    <div style="text-align:right">
        <p class="order-outcome-{{ $trade->outcome }}">{{ strtoupper($trade->outcome) }}</p>
        <p style="font-size:0.7rem;color:var(--client-muted);margin-top:0.35rem">{{ $trade->closed_at?->format('M d, H:i') }}</p>
    </div>
</button>
@empty
<div class="empty-state client-card">
    No metal trades yet.
    <p style="margin-top:0.75rem">
        <a href="{{ route('client.markets', ['tab' => 'metals']) }}">Browse metals</a>
        ·
        <a href="{{ route('client.trade', ['symbol' => 'XAUUSD']) }}">Trade gold</a>
    </p>
</div>
@endforelse

<dialog id="tradeReceiptModal" class="trade-receipt-modal">
    <div class="trade-receipt-card">
        <div class="trade-receipt-header">
            <div class="trade-receipt-title-row">
                <span class="trade-receipt-icon" aria-hidden="true"></span>
                <h2 class="trade-receipt-title">Trade Receipt</h2>
            </div>
            <div class="trade-receipt-header-actions">
                <span class="trade-receipt-badge" id="receiptBadge">—</span>
                <button type="button" class="trade-receipt-close" id="receiptClose" aria-label="Close">&times;</button>
            </div>
        </div>

        <p class="trade-receipt-section-label">Trade Details</p>
        <dl class="trade-receipt-rows">
            <div class="trade-receipt-row">
                <dt>Trade ID</dt>
                <dd id="receiptTradeId">—</dd>
            </div>
            <div class="trade-receipt-row">
                <dt>Pair</dt>
                <dd id="receiptPair">—</dd>
            </div>
            <div class="trade-receipt-row">
                <dt>Direction</dt>
                <dd id="receiptDirection">—</dd>
            </div>
            <div class="trade-receipt-row">
                <dt>Amount</dt>
                <dd id="receiptAmount">—</dd>
            </div>
            <div class="trade-receipt-row">
                <dt>Duration</dt>
                <dd id="receiptDuration">—</dd>
            </div>
            <div class="trade-receipt-row">
                <dt>Tick Price</dt>
                <dd id="receiptTickPrice">—</dd>
            </div>
        </dl>

        <p class="trade-receipt-section-label">Settlement Summary</p>
        <dl class="trade-receipt-rows">
            <div class="trade-receipt-row">
                <dt>Result</dt>
                <dd id="receiptResult">—</dd>
            </div>
            <div class="trade-receipt-row">
                <dt>Gross Payout</dt>
                <dd id="receiptGrossPayout">—</dd>
            </div>
            <div class="trade-receipt-row">
                <dt>Fees</dt>
                <dd id="receiptFees">—</dd>
            </div>
            <div class="trade-receipt-row">
                <dt>Net P&amp;L</dt>
                <dd id="receiptNetPnl">—</dd>
            </div>
            <div class="trade-receipt-row">
                <dt>Balance (Before)</dt>
                <dd id="receiptBalanceBefore">—</dd>
            </div>
            <div class="trade-receipt-row">
                <dt>Balance (After)</dt>
                <dd id="receiptBalanceAfter">—</dd>
            </div>
        </dl>
    </div>
</dialog>
@endsection

@push('scripts')
<script>
(function() {
    const receiptModal = document.getElementById('tradeReceiptModal');
    const receiptUrl = @json($receiptUrl);

    function formatAmount(value, currency) {
        if (value === null || value === undefined || Number.isNaN(Number(value))) {
            return '—';
        }
        return Number(value).toLocaleString(undefined, {
            minimumFractionDigits: 2,
            maximumFractionDigits: 8,
        }) + ' ' + currency;
    }

    function formatSignedPnl(value, currency) {
        if (value === null || value === undefined) return '—';
        const n = Number(value);
        const prefix = n >= 0 ? '+' : '';
        return prefix + Number(n).toLocaleString(undefined, {
            minimumFractionDigits: 2,
            maximumFractionDigits: 8,
        }) + ' ' + currency;
    }

    function fillReceipt(data) {
        const won = data.outcome === 'won';
        const currency = data.quote_currency;

        const badge = document.getElementById('receiptBadge');
        badge.textContent = data.result;
        badge.className = 'trade-receipt-badge trade-receipt-badge--' + (won ? 'won' : 'lost');

        document.getElementById('receiptTradeId').textContent = data.trade_id;
        document.getElementById('receiptPair').textContent = data.pair;
        document.getElementById('receiptDirection').textContent = data.direction;
        document.getElementById('receiptAmount').textContent = formatAmount(data.amount, currency);
        document.getElementById('receiptDuration').textContent = data.duration_seconds + ' s';
        document.getElementById('receiptTickPrice').textContent = data.tick_price != null
            ? formatAmount(data.tick_price, currency)
            : '— ' + currency;

        document.getElementById('receiptResult').textContent = data.result;
        document.getElementById('receiptGrossPayout').textContent = formatAmount(data.gross_payout, currency);
        document.getElementById('receiptFees').textContent = formatAmount(data.fees, currency);

        const netEl = document.getElementById('receiptNetPnl');
        netEl.textContent = formatSignedPnl(data.net_pnl, currency);
        netEl.classList.toggle('trade-receipt-value--positive', Number(data.net_pnl) >= 0);
        netEl.classList.toggle('trade-receipt-value--negative', Number(data.net_pnl) < 0);

        document.getElementById('receiptBalanceBefore').textContent = formatAmount(data.balance_before, currency);
        document.getElementById('receiptBalanceAfter').textContent = formatAmount(data.balance_after, currency);
    }

    async function openReceipt(tradeId) {
        const url = receiptUrl + '?trade_id=' + encodeURIComponent(String(tradeId));
        try {
            const res = await fetch(url, {
                credentials: 'same-origin',
                headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
            });
            const data = await res.json();
            if (!res.ok) throw new Error(data.message || 'Could not load receipt');
            fillReceipt(data);
            receiptModal.showModal();
        } catch (e) {
            alert(e.message || 'Could not load trade receipt');
        }
    }

    document.querySelectorAll('.order-card--clickable').forEach(function(card) {
        card.addEventListener('click', function() {
            openReceipt(this.dataset.tradeId);
        });
    });

    document.getElementById('receiptClose').addEventListener('click', function() {
        receiptModal.close();
    });

    receiptModal.addEventListener('click', function(e) {
        if (e.target === receiptModal) receiptModal.close();
    });
})();
</script>
@endpush
