<%- include('partials/page-start', { pageTitle, activePage }) %>

<% const num = (value) => Number(value || 0); %>
<% const totals = summary || { payments: {}, subscriptions: {}, product: {} }; %>
<% const trade = trading || { account: null, stats: {}, openPositions: [], recentTrades: [], coinPerformance: [], pagination: {}, dataAvailable: {} }; %>
<% const account = trade.account; %>
<% const tstats = trade.stats || {}; %>
<% const tradePagination = trade.pagination || { page: 1, pages: 1, total: 0 }; %>
<% const fmtQty = (value) => Number(value || 0).toLocaleString('en-US', { maximumFractionDigits: 8 }); %>
<% const fmtPct = (value) => `${Number(value || 0).toLocaleString('en-US', { maximumFractionDigits: 2 })}%`; %>
<% const hasValue = (value) => value !== null && value !== undefined; %>
<% const pnlClass = (value) => num(value) > 0 ? 'trade-positive' : (num(value) < 0 ? 'trade-negative' : 'trade-neutral'); %>
<% const tradePageUrl = (page) => `${adminUrl('/users/' + user.id)}?trade_page=${page}#trade-history`; %>

<div class="user-profile-back"><a href="<%= adminUrl('/users') %>">← Back to users</a></div>

<section class="user-profile-hero">
  <div class="user-profile-identity">
    <div class="user-profile-avatar" aria-hidden="true"><%= String(user.name || user.email || '?').trim().slice(0, 1).toUpperCase() %></div>
    <div class="user-profile-copy">
      <div class="dashboard-eyebrow">Trader profile</div>
      <h2><%= user.name || 'Unnamed user' %></h2>
      <p><%= user.email %></p>
      <div class="user-profile-badges">
        <span class="<%= Number(user.email_verified) === 1 ? 'badge badge-success' : 'badge badge-warning' %>"><%= Number(user.email_verified) === 1 ? 'Verified' : 'Not verified' %></span>
        <span class="badge badge-info"><%= user.plan_name || 'Free' %></span>
        <% if (Number(user.is_admin) === 1) { %><span class="badge badge-danger">Administrator</span><% } %>
      </div>
    </div>
  </div>
  <dl class="user-profile-meta">
    <div><dt>User ID</dt><dd>#<%= user.id %></dd></div>
    <div><dt>Registered</dt><dd><%= formatDate(user.created_at, false) %></dd></div>
    <div><dt>Last login</dt><dd><%= formatDate(user.last_login) %></dd></div>
    <div><dt>Trading account</dt><dd><%= account ? 'Active' : 'Not created' %></dd></div>
  </dl>
</section>

<% if (!trade.dataAvailable.trades && !trade.dataAvailable.positions) { %>
  <div class="user-trading-notice">Trading tables were not detected in the connected database. User and billing information is still available below.</div>
<% } %>

<section class="user-trading-kpis" aria-label="Trading performance">
  <article>
    <span>Account equity</span>
    <strong><%= account ? formatMoney(account.equity || account.balance || 0) : '—' %></strong>
    <small><%= account ? `Balance ${formatMoney(account.balance || 0)}` : 'No paper account' %></small>
  </article>
  <article>
    <span>Realized P&amp;L</span>
    <strong class="<%= pnlClass(tstats.realized_pnl) %>"><%= num(tstats.realized_pnl) > 0 ? '+' : '' %><%= formatMoney(tstats.realized_pnl || 0) %></strong>
    <small><%= num(tstats.pnl_trades).toLocaleString() %> trades with recorded P&amp;L</small>
  </article>
  <article>
    <span>Open P&amp;L</span>
    <% if (num(tstats.priced_positions) > 0) { %>
      <strong class="<%= pnlClass(tstats.unrealized_pnl) %>"><%= num(tstats.unrealized_pnl) > 0 ? '+' : '' %><%= formatMoney(tstats.unrealized_pnl || 0) %></strong>
      <small><%= num(tstats.priced_positions).toLocaleString() %> priced position(s)</small>
    <% } else { %>
      <strong>—</strong><small>No live price available</small>
    <% } %>
  </article>
  <article>
    <span>Win rate</span>
    <strong><%= fmtPct(tstats.win_rate) %></strong>
    <small><%= num(tstats.winning_trades).toLocaleString() %> wins / <%= num(tstats.losing_trades).toLocaleString() %> losses</small>
  </article>
  <article>
    <span>Open positions</span>
    <strong><%= num(tstats.open_positions).toLocaleString() %></strong>
    <small><%= formatMoney(tstats.open_invested || 0) %> invested</small>
  </article>
</section>

<section class="user-trading-snapshot">
  <div class="user-section-title">
    <div><span class="dashboard-eyebrow">Performance snapshot</span><h2>Trading account</h2></div>
    <span class="user-data-source"><span aria-hidden="true"></span>Live database data</span>
  </div>
  <dl>
    <div><dt>Total trades</dt><dd><%= num(tstats.total_trades).toLocaleString() %></dd></div>
    <div><dt>30-day trades</dt><dd><%= num(tstats.trades_30d).toLocaleString() %></dd></div>
    <div><dt>Trading volume</dt><dd><%= formatMoney(tstats.total_volume || 0) %></dd></div>
    <div><dt>Total fees</dt><dd><%= formatMoney(tstats.total_fees || 0) %></dd></div>
    <div><dt>Average P&amp;L</dt><dd class="<%= pnlClass(tstats.average_pnl) %>"><%= formatMoney(tstats.average_pnl || 0) %></dd></div>
    <div><dt>Active automations</dt><dd><%= num(tstats.active_tasks).toLocaleString() %></dd></div>
  </dl>
</section>

<section class="panel user-trading-panel" id="open-positions">
  <div class="panel-header">
    <div>
      <span class="dashboard-eyebrow">Current exposure</span>
      <h2 class="panel-title">Open positions</h2>
      <p class="panel-subtitle">Current holdings valued against the latest available market price.</p>
    </div>
    <span class="badge badge-info"><%= num(tstats.open_positions).toLocaleString() %> open</span>
  </div>
  <% if (!trade.openPositions.length) { %>
    <div class="empty-state">This user has no open positions.</div>
  <% } else { %>
    <div class="user-trading-table-wrap">
      <table class="user-trading-table">
        <thead><tr><th>Asset</th><th>Amount</th><th>Avg. entry</th><th>Current</th><th>Invested</th><th>Market value</th><th>Open P&amp;L</th><th>Return</th><th>Opened</th></tr></thead>
        <tbody>
          <% trade.openPositions.forEach((position) => { %>
            <tr>
              <td data-label="Asset"><strong><%= String(position.coin_symbol || position.coin_id || 'Unknown').toUpperCase() %></strong><small><%= position.coin_name || position.coin_id || '' %></small></td>
              <td data-label="Amount"><%= fmtQty(position.amount) %></td>
              <td data-label="Avg. entry"><%= formatMoney(position.avg_price || 0) %></td>
              <td data-label="Current"><%= hasValue(position.current_price) ? formatMoney(position.current_price) : '—' %></td>
              <td data-label="Invested"><%= formatMoney(position.invested || 0) %></td>
              <td data-label="Market value"><%= hasValue(position.market_value) ? formatMoney(position.market_value) : '—' %></td>
              <td data-label="Open P&amp;L" class="<%= hasValue(position.unrealized_pnl) ? pnlClass(position.unrealized_pnl) : '' %>"><%= hasValue(position.unrealized_pnl) ? `${num(position.unrealized_pnl) > 0 ? '+' : ''}${formatMoney(position.unrealized_pnl)}` : '—' %></td>
              <td data-label="Return" class="<%= hasValue(position.return_percent) ? pnlClass(position.return_percent) : '' %>"><%= hasValue(position.return_percent) ? `${num(position.return_percent) > 0 ? '+' : ''}${fmtPct(position.return_percent)}` : '—' %></td>
              <td data-label="Opened"><%= formatDate(position.created_at, false) %></td>
            </tr>
          <% }) %>
        </tbody>
      </table>
    </div>
  <% } %>
</section>

<section class="panel user-trading-panel" id="trade-history">
  <div class="panel-header">
    <div>
      <span class="dashboard-eyebrow">Execution history</span>
      <h2 class="panel-title">Trade history</h2>
      <p class="panel-subtitle">Every recorded buy and sell, newest first.</p>
    </div>
    <span class="badge badge-muted"><%= num(tradePagination.total).toLocaleString() %> total</span>
  </div>
  <% if (!trade.recentTrades.length) { %>
    <div class="empty-state">No trades were found for this user.</div>
  <% } else { %>
    <div class="user-trading-table-wrap">
      <table class="user-trading-table user-trade-history-table">
        <thead><tr><th>Trade</th><th>Side</th><th>Price</th><th>Amount</th><th>Total</th><th>Fee</th><th>Realized P&amp;L</th><th>Execution</th><th>Date</th></tr></thead>
        <tbody>
          <% trade.recentTrades.forEach((item) => { %>
            <tr>
              <td data-label="Trade"><strong><%= String(item.coin_symbol || item.coin_id || 'Unknown').toUpperCase() %></strong><small>#<%= item.id %><%= item.strategy ? ` · ${item.strategy}` : '' %></small></td>
              <td data-label="Side"><span class="trade-side trade-side-<%= String(item.type || '').toLowerCase() %>"><%= item.type || '—' %></span></td>
              <td data-label="Price"><%= hasValue(item.price) ? formatMoney(item.price) : '—' %></td>
              <td data-label="Amount"><%= fmtQty(item.amount) %></td>
              <td data-label="Total"><%= formatMoney(item.total || 0) %></td>
              <td data-label="Fee"><%= formatMoney(item.fee || 0) %></td>
              <td data-label="Realized P&amp;L" class="<%= hasValue(item.pnl) ? pnlClass(item.pnl) : '' %>"><%= hasValue(item.pnl) ? `${num(item.pnl) > 0 ? '+' : ''}${formatMoney(item.pnl)}` : '—' %></td>
              <td data-label="Execution"><span class="trade-execution"><%= item.execution_type || 'manual' %></span><% if (hasValue(item.confidence_score)) { %><small><%= fmtPct(item.confidence_score) %> confidence</small><% } %></td>
              <td data-label="Date"><%= formatDate(item.created_at) %></td>
            </tr>
          <% }) %>
        </tbody>
      </table>
    </div>
    <% if (num(tradePagination.pages) > 1) { %>
      <nav class="user-trade-pagination" aria-label="Trade history pages">
        <% if (num(tradePagination.page) > 1) { %><a href="<%= tradePageUrl(num(tradePagination.page) - 1) %>">← Previous</a><% } else { %><span></span><% } %>
        <span>Page <strong><%= tradePagination.page %></strong> of <strong><%= tradePagination.pages %></strong></span>
        <% if (num(tradePagination.page) < num(tradePagination.pages)) { %><a href="<%= tradePageUrl(num(tradePagination.page) + 1) %>">Next →</a><% } else { %><span></span><% } %>
      </nav>
    <% } %>
  <% } %>
</section>

<section class="user-profile-columns">
  <article class="panel">
    <div class="panel-header">
      <div><span class="dashboard-eyebrow">Asset breakdown</span><h2 class="panel-title">Performance by asset</h2><p class="panel-subtitle">Trade count, volume and realized result for each symbol.</p></div>
    </div>
    <% if (!trade.coinPerformance.length) { %>
      <div class="empty-state">No asset performance data.</div>
    <% } else { %>
      <div class="user-asset-list">
        <% trade.coinPerformance.forEach((asset) => { %>
          <% const decidedTrades = num(asset.winning_trades) + num(asset.losing_trades); %>
          <div class="user-asset-row">
            <span class="user-asset-symbol"><strong><%= String(asset.coin_symbol || asset.coin_id || '?').toUpperCase() %></strong><small><%= asset.coin_name || asset.coin_id || '' %></small></span>
            <span><small>Trades</small><strong><%= num(asset.total_trades).toLocaleString() %></strong></span>
            <span><small>Volume</small><strong><%= formatMoney(asset.total_volume || 0) %></strong></span>
            <span><small>Win rate</small><strong><%= decidedTrades ? fmtPct((num(asset.winning_trades) / decidedTrades) * 100) : '—' %></strong></span>
            <span><small>Realized P&amp;L</small><strong class="<%= pnlClass(asset.realized_pnl) %>"><%= num(asset.realized_pnl) > 0 ? '+' : '' %><%= formatMoney(asset.realized_pnl || 0) %></strong></span>
          </div>
        <% }) %>
      </div>
    <% } %>
  </article>

  <aside class="space-y-4">
    <article class="panel">
      <span class="dashboard-eyebrow">Account ledger</span>
      <h2 class="panel-title">Paper account totals</h2>
      <dl class="user-account-ledger">
        <div><dt>Balance</dt><dd><%= account ? formatMoney(account.balance || 0) : '—' %></dd></div>
        <div><dt>Equity</dt><dd><%= account ? formatMoney(account.equity || account.balance || 0) : '—' %></dd></div>
        <div><dt>Recorded profit</dt><dd class="trade-positive"><%= account ? formatMoney(account.total_profit || 0) : '—' %></dd></div>
        <div><dt>Recorded loss</dt><dd class="trade-negative"><%= account ? formatMoney(account.total_loss || 0) : '—' %></dd></div>
        <div><dt>Best trade</dt><dd class="<%= hasValue(tstats.best_trade) ? pnlClass(tstats.best_trade) : '' %>"><%= hasValue(tstats.best_trade) ? formatMoney(tstats.best_trade) : '—' %></dd></div>
        <div><dt>Worst trade</dt><dd class="<%= hasValue(tstats.worst_trade) ? pnlClass(tstats.worst_trade) : '' %>"><%= hasValue(tstats.worst_trade) ? formatMoney(tstats.worst_trade) : '—' %></dd></div>
      </dl>
    </article>

    <article class="panel">
      <span class="dashboard-eyebrow">Other activity</span>
      <h2 class="panel-title">Product signals</h2>
      <dl class="user-account-ledger">
        <div><dt>Active alerts</dt><dd><%= num(totals.product.active_alerts).toLocaleString() %></dd></div>
        <div><dt>Triggered alerts</dt><dd><%= num(totals.product.triggered_alerts).toLocaleString() %></dd></div>
        <div><dt>Active AI sessions</dt><dd><%= num(totals.product.active_ai_sessions).toLocaleString() %></dd></div>
        <div><dt>Watchlist items</dt><dd><%= num(totals.product.watchlist_items).toLocaleString() %></dd></div>
      </dl>
    </article>
  </aside>
</section>

<section class="user-profile-bottom-grid">
  <div class="space-y-4">
    <details class="user-profile-disclosure">
      <summary><span><strong>Subscriptions</strong><small>Current and previous membership records</small></span><span class="badge badge-muted"><%= subscriptions.length %></span></summary>
      <div class="user-profile-disclosure-body">
        <% if (!subscriptions.length) { %><div class="empty-state">No subscription records.</div><% } else { %>
          <div class="user-membership-list">
            <% subscriptions.forEach((sub) => { %>
              <div><span><strong><%= sub.plan_name %></strong><small><%= formatDate(sub.started_at, false) %> → <%= formatDate(sub.expires_at, false) %></small></span><span class="<%= statusBadgeClass(sub.status) %>"><%= sub.status %></span></div>
            <% }) %>
          </div>
        <% } %>
      </div>
    </details>

    <details class="user-profile-disclosure">
      <summary><span><strong>Transaction history</strong><small>Latest billing transactions and confirmed revenue</small></span><span class="badge badge-muted"><%= payments.length %></span></summary>
      <div class="user-profile-disclosure-body">
        <% if (!payments.length) { %><div class="empty-state">No transactions.</div><% } else { %>
          <div class="user-membership-list">
            <% payments.forEach((payment) => { %>
              <a href="<%= adminUrl('/payments/' + payment.id) %>"><span><strong>Order #<%= payment.order_id || payment.id %> · <%= payment.plan_name %></strong><small><%= formatDate(payment.created_at) %></small></span><span><strong><%= formatMoney(payment.payable_amount || payment.amount_usd, payment.currency || 'USD') %></strong><small class="<%= statusBadgeClass(payment.status) %>"><%= payment.status %></small></span></a>
            <% }) %>
          </div>
        <% } %>
      </div>
    </details>
  </div>

  <aside class="space-y-4" id="admin-controls">
    <article class="panel">
      <span class="dashboard-eyebrow">Membership control</span>
      <h2 class="panel-title">Change plan manually</h2>
      <p class="panel-subtitle">Creates a new subscription record when supported.</p>
      <form method="post" action="<%= adminUrl('/users/' + user.id + '/plan') %>" class="user-admin-form" data-confirm="Change this user's plan?">
        <input type="hidden" name="_csrf" value="<%= csrfToken %>">
        <label class="field"><span>New plan</span><select class="input" name="plan_id" required><option value="">Select plan</option><% plans.forEach((plan) => { %><option value="<%= plan.id %>" <%= Number(user.plan_id) === Number(plan.id) ? 'selected' : '' %>><%= plan.name %> · <%= formatMoney(plan.monthly_price || 0) %>/month</option><% }) %></select></label>
        <label class="field"><span>Duration (days)</span><input class="input" type="number" min="1" max="3650" name="duration_days" value="30" required></label>
        <button class="btn btn-primary w-full justify-center" type="submit">Update plan</button>
      </form>
    </article>

    <article class="panel user-admin-danger">
      <span class="dashboard-eyebrow">Security control</span>
      <h2 class="panel-title">Administrator access</h2>
      <p class="panel-subtitle">Grants full access to every administration route.</p>
      <form method="post" action="<%= adminUrl('/users/' + user.id + '/admin') %>" class="user-admin-form" data-confirm="<%= Number(user.is_admin) === 1 ? 'Remove administrator access from this user?' : 'Grant full administrator access to this user?' %>">
        <input type="hidden" name="_csrf" value="<%= csrfToken %>">
        <input type="hidden" name="make_admin" value="<%= Number(user.is_admin) === 1 ? '0' : '1' %>">
        <button class="btn <%= Number(user.is_admin) === 1 ? 'btn-danger' : 'btn-primary' %> w-full justify-center" type="submit"><%= Number(user.is_admin) === 1 ? 'Remove admin access' : 'Make administrator' %></button>
      </form>
    </article>
  </aside>
</section>

<%- include('partials/page-end', { activePage }) %>
