<?php
/**
 * VALIDATION TRACKER — the developing trader's simple progress center.
 * ─────────────────────────────────────────────────────────────────
 * Renamed from "Validation Journal" per the Validation Workflow spec
 * (§9): this page's job is NOT to be another journal (public/journal.php
 * already shows validation trades when the user's workflow is
 * 'validation' — see that file's workflow-aware is_validation scoping).
 * This page answers one question: "does this developing strategy have
 * enough reliable evidence yet to become the trader's real edge?"
 *
 * Every performance number on this page comes from
 * ValidationService::getMetrics()/getProgress() (src/ValidationService.php),
 * which themselves delegate to AnalyticsEngine::getValidationStrategyMetrics()
 * (api/analytics/engine.php) — the same canonical calculation layer every
 * other page in this app reads from. This file computes zero trading math
 * of its own (the old inline win-rate/expectancy/profit-factor/avg-R
 * formulas here were a Single-Source-of-Truth violation — removed).
 *
 * Graduation (the old inline POST action=promote handler here never
 * actually worked — this route was GET-only in index.php, so that form's
 * POST had nowhere to land) now goes through POST /api/validation/graduate
 * via fetch(), which calls ValidationService::graduate() — the one real,
 * atomic, server-side-capped graduation path in the app.
 */
$userId = $auth->requireAuth();

$validationDisplayName = resolveDisplayName($db->selectById('user_profiles', $userId, 'user_id'));

function navUrl($strategyId = null, $tradeId = null) {
    $params = [];
    if ($strategyId) $params['strategy'] = $strategyId;
    if ($tradeId) $params['id'] = $tradeId;
    $query = !empty($params) ? '?' . http_build_query($params) : '';
    return '/traderalign/journal-validation' . $query;
}

// pnlClass()/pnlFormat() live in src/RenderHelpers.php (required globally by index.php).

// ─────────────────────────────────────────────────────────────
// Validation strategies — single source: ValidationService.
// ─────────────────────────────────────────────────────────────
$validationStrategies = ValidationService::getValidationStrategies($userId, $db);

$selectedStrategyId = $_GET['strategy'] ?? null;
$selectedTradeId = $_GET['id'] ?? null;
$metricPeriod = in_array($_GET['period'] ?? 'all', ['all', 'weekly', 'monthly', 'quarterly'], true) ? ($_GET['period'] ?? 'all') : 'all';

// Auto-select first strategy if none chosen
if (!$selectedStrategyId && !empty($validationStrategies)) {
    $selectedStrategyId = $validationStrategies[0]['id'];
}

$focusStrategy = null;
if ($selectedStrategyId) {
    foreach ($validationStrategies as $s) {
        if ($s['id'] === $selectedStrategyId) {
            $focusStrategy = $s;
            break;
        }
    }
}

// ─────────────────────────────────────────────────────────────
// Metrics + progress for the focused strategy — canonical, via
// ValidationService (which itself only ever delegates to AnalyticsEngine).
// ─────────────────────────────────────────────────────────────
$validationMetrics = null;
$progress = null;
$trades = [];
$selectedTrade = null;

if ($focusStrategy) {
    $progress = ValidationService::getProgress($userId, $focusStrategy['version_id'], $db);

    [$periodStart, $periodEnd] = ValidationService::periodBounds($metricPeriod);
    $validationMetrics = ValidationService::getMetrics($userId, $focusStrategy['version_id'], $periodStart, $periodEnd);

    // Edge evaluation (2026-08-12 pass) — ALWAYS computed from the
    // all-time metrics (never the period-scoped $validationMetrics above,
    // which can be an empty/thin slice if a Weekly/Monthly view is
    // active), since graduation eligibility is a whole-strategy question,
    // not a period one. ValidationService::graduate() re-computes this
    // exact same all-time evaluation itself, server-side, so this is
    // purely for rendering the right card — the server never trusts this.
    $allTimeMetricsForEdge = $metricPeriod === 'all'
        ? $validationMetrics
        : ValidationService::getMetrics($userId, $focusStrategy['version_id']);
    $edgeEval = ValidationService::evaluateEdge($allTimeMetricsForEdge);

    // 50-trade Strategy Review — same shared card Reports shows for a
    // graduated strategy (src/StrategyMilestoneReview.php), so a trader
    // watching this strategy approach/cross 50 trades here sees the exact
    // same interpretive assessment they'll see again on Reports once it
    // graduates. Null below 50 trades (renders nothing). true = validation
    // scope, matching this page's own is_validation=1 trade queries above.
    $milestoneReview = StrategyMilestoneReview::build(
        $userId, $db,
        ['id' => $focusStrategy['id'], 'name' => $focusStrategy['name'], 'current_version_id' => $focusStrategy['version_id']],
        $validationDisplayName, true
    );

    // Trade list — display only, not a metrics source. Same effective_pnl
    // cascade every other trade list in the app uses.
    $trades = $db->raw(
        "SELECT t.*,
                (SELECT COUNT(*) FROM trade_screenshots ts WHERE ts.trade_id = t.id) AS screenshot_count,
                CASE WHEN ta.account_type = 'prop_firm' THEN t.challenge_pnl ELSE t.broker_pnl END AS effective_pnl
         FROM trades t
         LEFT JOIN trading_accounts ta ON ta.id = t.account_id
         WHERE t.strategy_version_id = :vid
           AND t.user_id = :uid
           AND t.is_validation = 1
           AND t.status = 'closed'
           AND t.deleted_at IS NULL
         ORDER BY t.closed_at DESC",
        [':vid' => $focusStrategy['version_id'], ':uid' => $userId]
    );
}

// Get selected trade details
if ($selectedTradeId && $focusStrategy) {
    $selectedTrade = $db->raw(
        "SELECT t.*,
                (SELECT COUNT(*) FROM trade_screenshots ts WHERE ts.trade_id = t.id) AS screenshot_count,
                CASE WHEN ta.account_type = 'prop_firm' THEN t.challenge_pnl ELSE t.broker_pnl END AS effective_pnl
         FROM trades t
         LEFT JOIN trading_accounts ta ON ta.id = t.account_id
         WHERE t.id = :tid AND t.user_id = :uid AND t.strategy_version_id = :vid AND t.is_validation = 1 AND t.deleted_at IS NULL",
        [':tid' => $selectedTradeId, ':uid' => $userId, ':vid' => $focusStrategy['version_id']]
    );
    $selectedTrade = $selectedTrade[0] ?? null;
}

$periodLabels = ['all' => 'All-Time', 'weekly' => 'This Week', 'monthly' => 'This Month', 'quarterly' => 'This Quarter'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Validation Tracker - TraderAlign</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/traderalign/assets/tokens.css">
<link rel="icon" type="image/png" sizes="32x32" href="/traderalign/assets/favicon/favicon-32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/traderalign/assets/favicon/favicon-16.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/traderalign/assets/favicon/apple-touch-icon.png">
    <link rel="shortcut icon" href="/traderalign/assets/favicon/favicon.ico">
<link rel="stylesheet" href="/traderalign/assets/css/brand.css">
<link rel="stylesheet" href="/traderalign/assets/css/trade-screenshots.css">
<script src="/traderalign/assets/js/trade-screenshots.js"></script>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:var(--font-sans);background:var(--background);color:var(--foreground);-webkit-font-smoothing:antialiased}
.dash-layout{display:flex;min-height:100vh}
.sidebar{width:4rem;background:var(--sidebar);border-right:1px solid var(--sidebar-border);display:flex;flex-direction:column;align-items:center;padding-top:1rem;gap:.25rem;position:fixed;top:0;left:0;bottom:0;z-index:40}
.sidebar a{display:flex;align-items:center;justify-content:center;width:2.75rem;height:2.75rem;border-radius:var(--radius-md);color:var(--foreground-dim);transition:background var(--t-fast),color var(--t-fast);position:relative}
.sidebar a:hover{background:var(--background-surface);color:var(--foreground)}
.sidebar a.active{background:var(--background-surface);color:var(--sidebar-primary)}
.sidebar a .tt{position:absolute;left:3.5rem;background:var(--popover);color:var(--foreground);font-size:.75rem;padding:.25rem .625rem;border-radius:var(--radius-sm);white-space:nowrap;pointer-events:none;opacity:0;transition:opacity var(--t-fast)}
.sidebar a:hover .tt{opacity:1}
.main{margin-left:4rem;flex:1;padding:2rem;max-width:calc(100vw - 4rem)}
.page-title{font-size:1.5rem;font-weight:800;color:var(--foreground);letter-spacing:-.02em}
.page-sub{font-size:.78rem;color:var(--foreground-dim);margin-top:.15rem;margin-bottom:1.5rem}

/* Strategy selector tabs */
.strategy-tabs{display:flex;gap:.4rem;margin-bottom:1.5rem;flex-wrap:wrap;padding-bottom:1rem;border-bottom:1px solid var(--border)}
.strategy-tab{padding:.55rem 1rem;border-radius:var(--radius-full);font-size:.78rem;font-weight:600;text-decoration:none;color:var(--foreground-dim);background:var(--background-surface);border:1px solid var(--border);display:flex;align-items:center;gap:.5rem}
.strategy-tab:hover{color:var(--foreground);border-color:color-mix(in srgb,var(--primary) 30%,transparent)}
.strategy-tab.active{background:color-mix(in srgb,var(--primary) 15%,transparent);color:var(--primary);border-color:color-mix(in srgb,var(--primary) 40%,transparent)}
.strategy-tab .tab-count{font-family:var(--font-mono);font-size:.65rem;opacity:.7}

/* Period toggle */
.period-toggle{display:flex;gap:.4rem;margin-bottom:1rem}
.period-pill{padding:.4rem .85rem;border-radius:var(--radius-full);font-size:.72rem;font-weight:600;text-decoration:none;color:var(--foreground-dim);background:var(--background-surface);border:1px solid var(--border)}
.period-pill:hover{color:var(--foreground)}
.period-pill.active{background:color-mix(in srgb,var(--primary) 15%,transparent);color:var(--primary);border-color:color-mix(in srgb,var(--primary) 40%,transparent)}

/* Progress tracker */
.progress-card{background:var(--background-elevated);border:1px solid var(--border);border-radius:var(--radius-xl);padding:1.5rem 1.75rem;margin-bottom:1.5rem}
.progress-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:1rem}
.progress-title{font-size:1.05rem;font-weight:700;color:var(--foreground)}
.progress-target{font-size:.72rem;color:var(--foreground-dim);font-family:var(--font-mono)}
.progress-bar-container{height:8px;background:var(--background-surface);border-radius:var(--radius-full);overflow:hidden;margin-bottom:1.25rem}
.progress-bar-fill{height:100%;background:linear-gradient(90deg,var(--primary),color-mix(in srgb,var(--primary) 70%,var(--positive)));border-radius:var(--radius-full);transition:width .4s ease}
.progress-bar-fill.complete{background:linear-gradient(90deg,var(--positive),#10b981)}
.period-note{font-size:.7rem;color:var(--foreground-dim);margin-bottom:1rem}

.metrics-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:1rem}
.metric-item{background:var(--background-surface);border:1px solid var(--border);border-radius:var(--radius-lg);padding:.85rem 1rem;text-align:center}
.metric-label{font-size:.62rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--foreground-dim);margin-bottom:.25rem}
.metric-value{font-family:var(--font-mono);font-size:1.1rem;font-weight:700;color:var(--foreground)}
.metric-value.positive{color:var(--positive)}
.metric-value.negative{color:var(--negative)}
.metric-value.neutral{color:var(--foreground-dim)}

/* Promotion UI */
.promotion-card{background:linear-gradient(145deg,color-mix(in srgb,var(--positive) 8%,transparent),color-mix(in srgb,var(--primary) 5%,transparent));border:2px solid color-mix(in srgb,var(--positive) 30%,transparent);border-radius:var(--radius-xl);padding:1.5rem 1.75rem;margin-bottom:1.5rem}
.promotion-card.at-cap{border-color:color-mix(in srgb,var(--warning) 40%,transparent);background:linear-gradient(145deg,color-mix(in srgb,var(--warning) 8%,transparent),color-mix(in srgb,var(--primary) 5%,transparent))}
.promotion-card.edge-warning{border-color:color-mix(in srgb,var(--negative) 40%,transparent);background:linear-gradient(145deg,color-mix(in srgb,var(--negative) 8%,transparent),color-mix(in srgb,var(--warning) 5%,transparent))}
.promotion-title{font-size:1.1rem;font-weight:700;color:var(--positive);margin-bottom:.5rem}
.promotion-card.at-cap .promotion-title{color:var(--warning)}
.promotion-card.edge-warning .promotion-title{color:var(--negative)}
.promotion-detail{font-size:.82rem;color:var(--foreground-dim);line-height:1.6;margin-bottom:1rem}
.promotion-actions{display:flex;gap:.75rem;flex-wrap:wrap}
.btn-promote{display:inline-flex;align-items:center;gap:.5rem;padding:.65rem 1.25rem;border-radius:var(--radius-lg);font-size:.8rem;font-weight:600;color:#fff;background:var(--positive);border:none;cursor:pointer;transition:all .2s ease;font-family:var(--font-sans)}
.btn-promote:hover{opacity:.9;transform:translateY(-1px)}
.btn-promote:disabled{opacity:.6;cursor:wait}
.btn-promote.edge-warning-btn{background:var(--background-surface);color:var(--negative);border:1px solid color-mix(in srgb,var(--negative) 40%,transparent)}
.btn-promote.edge-warning-btn:hover{background:color-mix(in srgb,var(--negative) 10%,transparent)}
.btn-continue{display:inline-flex;align-items:center;gap:.5rem;padding:.65rem 1.25rem;border-radius:var(--radius-lg);font-size:.8rem;font-weight:600;color:var(--foreground);background:var(--background-surface);border:1px solid var(--border);cursor:pointer;transition:all .2s ease;font-family:var(--font-sans);text-decoration:none}
.btn-continue:hover{border-color:var(--foreground-dim)}

/* Trade list */
.section-label{font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.12em;color:var(--foreground-dim);margin-bottom:.85rem;padding-bottom:.5rem;border-bottom:2px solid var(--border);display:flex;justify-content:space-between;align-items:center}
.trade-row{display:flex;align-items:center;justify-content:space-between;background:var(--background-elevated);border:1px solid var(--border);border-radius:var(--radius-lg);padding:.85rem 1.1rem;margin-bottom:.55rem;text-decoration:none;color:inherit;transition:border-color .15s}
.trade-row:hover{border-color:color-mix(in srgb,var(--primary) 25%,transparent)}
.trade-left{display:flex;flex-direction:column;gap:.2rem}
.trade-instrument{font-weight:700;font-size:.85rem}
.trade-meta{font-size:.68rem;color:var(--foreground-dim)}
.trade-pnl{font-family:var(--font-mono);font-weight:600;font-size:.8rem}
.status-pill{font-size:.6rem;font-weight:700;text-transform:uppercase;padding:.15rem .5rem;border-radius:var(--radius-full);background:var(--background-surface);color:var(--foreground-dim);border:1px solid var(--border)}
.pill-green{background:color-mix(in srgb,var(--positive) 18%,transparent);color:var(--positive);border-color:color-mix(in srgb,var(--positive) 25%,transparent)}
.pill-red{background:color-mix(in srgb,var(--negative) 18%,transparent);color:var(--negative);border-color:color-mix(in srgb,var(--negative) 25%,transparent)}
.pill-neutral{background:var(--background-surface);color:var(--foreground-dim);border:1px solid var(--border)}
.positive{color:var(--positive)} .negative{color:var(--negative)}

/* Trade detail */
.back-link{font-size:.82rem;color:var(--primary);text-decoration:none;margin-bottom:1rem;display:inline-block}
.detail-card{background:var(--background-elevated);border:1px solid var(--border);border-radius:var(--radius-xl);padding:1.5rem 1.75rem;margin-bottom:1rem}
.detail-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:1rem}
.detail-instrument{font-size:1.15rem;font-weight:800;color:var(--foreground)}
.detail-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:.75rem}
.detail-row{display:flex;justify-content:space-between;padding:.5rem 0;border-bottom:1px solid color-mix(in srgb,var(--border) 30%,transparent)}
.detail-label{color:var(--foreground-dim);font-size:.78rem}
.detail-value{font-family:var(--font-mono);font-weight:500;font-size:.82rem}

.empty-state{text-align:center;padding:4rem 1rem;color:var(--foreground-dim)}
.empty-state h3{font-size:1.1rem;color:var(--foreground);margin-bottom:.5rem}

.error-banner{background:color-mix(in srgb,var(--negative) 8%,transparent);border:1px solid color-mix(in srgb,var(--negative) 25%,transparent);border-radius:var(--radius-md);padding:.75rem 1rem;margin-bottom:1rem;font-size:.78rem;color:var(--negative)}

@media(max-width:768px){
  .main{padding:1rem}
  .metrics-grid{grid-template-columns:repeat(2,1fr)}
  .detail-grid{grid-template-columns:1fr}
  .strategy-tabs{overflow-x:auto;flex-wrap:nowrap}
}
</style>
</head>
<body class="dash-layout">
<?php require __DIR__ . '/sidebar.php'; ?>
<main class="main">

<h1 class="page-title">🔬 Validation Tracker</h1>
<div class="page-sub">Your simple progress center, tracking whether this developing strategy has enough reliable evidence to become your real edge.</div>

<div id="graduate-error" class="error-banner" style="display:none"></div>

<?php if (empty($validationStrategies)): ?>
<div class="empty-state">
    <h3>No validation strategies yet</h3>
    <p style="font-size:.85rem;margin-bottom:1rem">Create a validation strategy to start tracking your edge development.</p>
    <a href="/traderalign/strategy-validation" class="btn-continue" style="display:inline-flex">Create Validation Strategy</a>
</div>

<?php else: ?>

<!-- Strategy selector tabs -->
<div class="strategy-tabs">
    <?php foreach ($validationStrategies as $s): ?>
    <a href="<?= navUrl($s['id']) ?>" class="strategy-tab <?= $selectedStrategyId === $s['id'] ? 'active' : '' ?>">
        <?= htmlspecialchars($s['name']) ?>
        <span class="tab-count"><?= $s['trade_count'] ?> trades</span>
    </a>
    <?php endforeach; ?>
</div>

<?php if ($focusStrategy && $validationMetrics && $progress): ?>

<!-- Period toggle -->
<div class="period-toggle">
    <?php foreach ($periodLabels as $pKey => $pLabel): ?>
    <a href="<?= navUrl($focusStrategy['id']) ?>&amp;period=<?= $pKey ?>" class="period-pill <?= $metricPeriod === $pKey ? 'active' : '' ?>"><?= $pLabel ?></a>
    <?php endforeach; ?>
</div>

<!-- Progress Tracker -->
<div class="progress-card">
    <div class="progress-header">
        <span class="progress-title"><?= htmlspecialchars($focusStrategy['name']) ?></span>
        <span class="progress-target"><?= $progress['trade_count'] ?> of <?= $progress['at_cap'] ? $progress['max'] . ' (max)' : $progress['target'] ?> trades</span>
    </div>
    <div class="progress-bar-container">
        <div class="progress-bar-fill <?= $progress['progress_pct'] >= 100 ? 'complete' : '' ?>"
             style="width:<?= $progress['progress_pct'] ?>%"></div>
    </div>
    <?php if ($metricPeriod !== 'all'): ?>
    <div class="period-note">Metrics below are scoped to <?= strtolower($periodLabels[$metricPeriod]) ?>. Trade count and progress above are always all-time.</div>
    <?php endif; ?>

    <div class="metrics-grid">
        <div class="metric-item">
            <div class="metric-label">Win Rate</div>
            <div class="metric-value <?= $validationMetrics['win_rate'] >= 0.5 ? 'positive' : 'negative' ?>">
                <?= round($validationMetrics['win_rate'] * 100, 1) ?>%
            </div>
        </div>
        <div class="metric-item">
            <div class="metric-label" title="<?= $validationMetrics['avg_r_multiple'] === null ? 'No closed trades with a recorded stop-loss/exit yet' : '' ?>">Average R<?= $validationMetrics['avg_r_multiple'] === null ? ' ⓘ' : '' ?></div>
            <div class="metric-value <?= $validationMetrics['avg_r_multiple'] === null ? 'neutral' : ($validationMetrics['avg_r_multiple'] >= 1 ? 'positive' : 'negative') ?>">
                <?= $validationMetrics['avg_r_multiple'] !== null ? number_format($validationMetrics['avg_r_multiple'], 2) . 'R' : '-' ?>
            </div>
        </div>
        <div class="metric-item">
            <div class="metric-label">Expectancy</div>
            <div class="metric-value <?= $validationMetrics['expectancy'] > 0 ? 'positive' : ($validationMetrics['expectancy'] < 0 ? 'negative' : 'neutral') ?>">
                <?= $validationMetrics['expectancy'] > 0 ? '+' : '' ?><?= number_format($validationMetrics['expectancy'], 2) ?>
            </div>
        </div>
        <div class="metric-item">
            <div class="metric-label" title="<?= $validationMetrics['profit_factor'] === null ? 'Not enough losing trades yet to calculate' : '' ?>">Profit Factor<?= $validationMetrics['profit_factor'] === null ? ' ⓘ' : '' ?></div>
            <div class="metric-value <?= $validationMetrics['profit_factor'] === null ? 'neutral' : ($validationMetrics['profit_factor'] >= 1.5 ? 'positive' : ($validationMetrics['profit_factor'] >= 1 ? '' : 'negative')) ?>">
                <?= $validationMetrics['profit_factor'] !== null ? number_format($validationMetrics['profit_factor'], 2) : '-' ?>
            </div>
        </div>
        <div class="metric-item">
            <div class="metric-label">Wins</div>
            <div class="metric-value positive"><?= $validationMetrics['win_count'] ?></div>
        </div>
        <div class="metric-item">
            <div class="metric-label">Losses</div>
            <div class="metric-value negative"><?= $validationMetrics['loss_count'] ?></div>
        </div>
        <div class="metric-item">
            <div class="metric-label" title="<?= $validationMetrics['rule_adherence_pct'] === null ? 'No trades with a saved checklist result yet' : '' ?>">Rule Adherence<?= $validationMetrics['rule_adherence_pct'] === null ? ' ⓘ' : '' ?></div>
            <div class="metric-value <?= $validationMetrics['rule_adherence_pct'] === null ? 'neutral' : ($validationMetrics['rule_adherence_pct'] >= 80 ? 'positive' : ($validationMetrics['rule_adherence_pct'] >= 60 ? '' : 'negative')) ?>">
                <?= $validationMetrics['rule_adherence_pct'] !== null ? $validationMetrics['rule_adherence_pct'] . '%' : '-' ?>
            </div>
        </div>
        <div class="metric-item">
            <div class="metric-label">Breakevens</div>
            <div class="metric-value neutral"><?= $validationMetrics['breakeven_count'] ?></div>
        </div>
    </div>
</div>

<?php if ($milestoneReview): StrategyMilestoneReview::renderCard($milestoneReview, 'tracker'); endif; ?>

<!-- Graduation CTA — spec §12: hidden below 50, both actions 50-99, only
     "Enter Main Workflow" (no "continue") at 100. 2026-08-12: at 50+, the
     strategy's ALL-TIME expectancy/profit-factor (evaluateEdge(), the same
     canonical numbers this page's own metric tiles already show — no
     second formula) decides which of two cards renders. -->
<?php if ($progress['eligible_to_graduate']): ?>

<?php if ($edgeEval['demonstrated'] === false): ?>
<!-- Edge NOT demonstrated — explicit warning, "Continue Anyway" still
     available (never a hard block) but requires acknowledging the warning. -->
<div class="promotion-card edge-warning">
    <div class="promotion-title">⚠️ This strategy has not yet demonstrated a profitable edge</div>
    <div class="promotion-detail">
        Across <b><?= $progress['trade_count'] ?></b> validation trades, this strategy's expectancy is
        <b class="<?= $edgeEval['expectancy'] > 0 ? 'positive' : 'negative' ?>"><?= $edgeEval['expectancy'] > 0 ? '+' : '' ?><?= number_format($edgeEval['expectancy'], 2) ?> per trade</b><?php if ($edgeEval['profit_factor'] !== null): ?>
        with a profit factor of <b><?= number_format($edgeEval['profit_factor'], 2) ?></b><?php endif; ?>.
        The data so far does not show a reliable, profitable edge. We recommend continuing to validate rather than moving this strategy into the main workflow yet.
    </div>
    <div class="promotion-detail" style="font-size:.76rem">
        <?= $progress['trade_count'] ?> trades is only an initial validation sample. Performance can still change, for better or worse, with more data (100-1,000 trades is a much more reliable read than <?= $progress['trade_count'] ?>). If you're confident in this strategy and want to keep gathering evidence, <b>Continue Validating</b> is the safer choice. If you choose to continue anyway, TraderAlign will keep tracking this strategy's real performance in the main workflow and will tell you plainly if it later shows "Improving," a demonstrated edge, or further deterioration. This warning does not mean the strategy is permanently written off, only that it hasn't proven itself <i>yet</i>.
    </div>
    <div class="promotion-actions">
        <?php if (!$progress['at_cap']): ?>
        <a href="<?= navUrl($focusStrategy['id']) ?>" class="btn-continue">Continue Validating</a>
        <?php endif; ?>
        <button type="button" class="btn-promote edge-warning-btn" id="graduate-btn" onclick="graduateStrategy('<?= htmlspecialchars($focusStrategy['id']) ?>', this, true)">Continue Anyway →</button>
    </div>
</div>
<?php else: ?>
<!-- Edge demonstrated (or not yet classifiable, e.g. zero trades — can't
     happen here since eligible_to_graduate implies >=50 closed trades) —
     graduation proceeds normally, no warning. -->
<div class="promotion-card <?= $progress['at_cap'] ? 'at-cap' : '' ?>">
    <?php if ($progress['at_cap']): ?>
    <div class="promotion-title">You've reached the validation ceiling</div>
    <div class="promotion-detail">
        You've completed <b><?= $progress['trade_count'] ?></b> trades, the maximum for the validation workflow.
        You now have enough evidence to establish a starting point for your trading edge. It's time to enter the main workflow with this strategy.
    </div>
    <?php else: ?>
    <div class="promotion-title">🎉 Your initial validation sample is complete</div>
    <div class="promotion-detail">
        You've completed <b><?= $progress['trade_count'] ?></b> trades with a win rate of <b><?= round($validationMetrics['win_rate'] * 100, 1) ?>%</b>.
        You now have enough data to establish a starting point for your trading edge.
    </div>
    <?php endif; ?>
    <div class="promotion-actions">
        <button type="button" class="btn-promote" id="graduate-btn" onclick="graduateStrategy('<?= htmlspecialchars($focusStrategy['id']) ?>', this, false)">🚀 Enter Main Workflow</button>
        <?php if (!$progress['at_cap']): ?>
        <a href="<?= navUrl($focusStrategy['id']) ?>" class="btn-continue">Continue Validating</a>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<?php endif; ?>

<!-- Trade detail view -->
<?php if ($selectedTradeId && $selectedTrade): ?>
<a href="<?= navUrl($focusStrategy['id']) ?>" class="back-link">← Back to trade list</a>

<div class="detail-card">
    <div class="detail-header">
        <span class="detail-instrument">
            <?= htmlspecialchars($selectedTrade['instrument']) ?>
            <span class="<?= $selectedTrade['direction'] === 'long' ? 'positive' : 'negative' ?>" style="font-size:.85rem">
                <?= strtoupper($selectedTrade['direction']) ?>
            </span>
        </span>
        <span style="font-family:var(--font-mono);font-weight:700;font-size:1rem" class="<?= pnlClass(floatval($selectedTrade['effective_pnl'] ?? 0)) ?>">
            <?= pnlFormat(floatval($selectedTrade['effective_pnl'] ?? 0)) ?>
        </span>
    </div>

    <div class="detail-grid">
        <div class="detail-row">
            <span class="detail-label">Status</span>
            <span class="detail-value"><?= htmlspecialchars(ucfirst($selectedTrade['status'] ?? 'unknown')) ?></span>
        </div>
        <div class="detail-row">
            <span class="detail-label">Entry Price</span>
            <span class="detail-value"><?= number_format(floatval($selectedTrade['entry_price'] ?? 0), 5) ?></span>
        </div>
        <div class="detail-row">
            <span class="detail-label">Exit Price</span>
            <span class="detail-value"><?= number_format(floatval($selectedTrade['actual_exit_price'] ?? 0), 5) ?></span>
        </div>
        <div class="detail-row">
            <span class="detail-label">Risk %</span>
            <span class="detail-value"><?= round(floatval($selectedTrade['risk_pct'] ?? 0), 2) ?>%</span>
        </div>
        <div class="detail-row">
            <span class="detail-label">Classification</span>
            <span class="detail-value">
                <?php if (!empty($selectedTrade['trade_classification'])): ?>
                <span class="status-pill <?= match($selectedTrade['trade_classification']) {
                    'disciplined_win' => 'pill-green',
                    'controlled_loss', 'breakeven' => 'pill-neutral',
                    'loss_high_risk', 'tilt_warning', 'revenge_trade' => 'pill-red',
                    default => ''
                } ?>"><?= htmlspecialchars(str_replace('_', ' ', $selectedTrade['trade_classification'])) ?></span>
                <?php else: ?>
                <span style="color:var(--foreground-dim)">-</span>
                <?php endif; ?>
            </span>
        </div>
        <div class="detail-row">
            <span class="detail-label">Opened</span>
            <span class="detail-value"><?= htmlspecialchars(substr($selectedTrade['captured_at'] ?? '', 0, 16)) ?></span>
        </div>
        <div class="detail-row">
            <span class="detail-label">Closed</span>
            <span class="detail-value"><?= htmlspecialchars(substr($selectedTrade['closed_at'] ?? '-', 0, 16)) ?></span>
        </div>
        <div class="detail-row">
            <span class="detail-label">SL Price</span>
            <span class="detail-value"><?= number_format(floatval($selectedTrade['sl_price'] ?? 0), 5) ?></span>
        </div>
    </div>
</div>

<?php else: ?>

<!-- Trade list -->
<div class="section-label">
    <span>Validation Trades</span>
    <span style="font-weight:400;text-transform:none;letter-spacing:0"><?= $progress['trade_count'] ?> closed</span>
</div>

<?php if (empty($trades)): ?>
<div class="empty-state" style="padding:2rem">
    <p style="font-size:.85rem;color:var(--foreground-dim)">No closed trades yet. Start trading this strategy to build your validation data.</p>
</div>
<?php else: ?>
<?php foreach ($trades as $t):
    $tPnl = floatval($t['effective_pnl'] ?? 0);
    $classification = $t['trade_classification'] ?? null;
    $tScreenshotCount = (int)($t['screenshot_count'] ?? 0);
?>
<div class="trade-row" style="text-decoration:none">
    <a href="<?= navUrl($focusStrategy['id'], $t['id']) ?>" style="display:flex;flex:1;align-items:center;text-decoration:none;color:inherit;min-width:0">
    <div class="trade-left">
        <div class="trade-instrument">
            <?= htmlspecialchars($t['instrument']) ?>
            <span class="<?= $t['direction'] === 'long' ? 'positive' : 'negative' ?>" style="font-size:.7rem">
                <?= strtoupper($t['direction']) ?>
            </span>
        </div>
        <div class="trade-meta">
            Closed <?= htmlspecialchars(substr($t['closed_at'] ?? '', 0, 10)) ?>
            <?php if ($classification): ?>
            · <span class="status-pill <?= match($classification) {
                'disciplined_win' => 'pill-green',
                'controlled_loss', 'breakeven' => 'pill-neutral',
                'loss_high_risk', 'tilt_warning', 'revenge_trade' => 'pill-red',
                default => ''
            } ?>"><?= htmlspecialchars(str_replace('_', ' ', $classification)) ?></span>
            <?php endif; ?>
        </div>
    </div>
    <span class="trade-pnl <?= pnlClass($tPnl) ?>"><?= pnlFormat($tPnl) ?></span>
    </a>
    <span class="rn-screenshot-badge<?= $tScreenshotCount === 0 ? ' rn-screenshot-badge-empty' : '' ?>" data-trade-id="<?= htmlspecialchars($t['id']) ?>" title="Upload or view screenshots for this trade" style="margin-left:.6rem;flex-shrink:0" onclick="event.preventDefault();event.stopPropagation();rnOpenScreenshotModal('<?= htmlspecialchars($t['id']) ?>')"><?= $tScreenshotCount > 0 ? '📷 ' . $tScreenshotCount : '+ Add' ?></span>
</div>
<?php endforeach; ?>
<?php endif; ?>

<?php endif; ?>

<?php else: ?>
<div class="empty-state">
    <h3>Strategy not found</h3>
    <p style="font-size:.85rem">Select a validation strategy from the tabs above.</p>
</div>
<?php endif; ?>

<?php endif; ?>

<script>
// force (2026-08-12): true only on the edge-warning card's "Continue
// Anyway" button (server-rendered above only when evaluateEdge() already
// found no demonstrated edge). The server re-checks this exact same
// evaluation itself (ValidationService::graduate()) — force is never
// trusted alone to skip the check, only to explicitly acknowledge it.
function graduateStrategy(strategyId, btn, force) {
    var defaultLabel = force ? 'Continue Anyway →' : '🚀 Enter Main Workflow';
    var confirmMsg = force
        ? 'Continue anyway? This strategy has not yet demonstrated a profitable edge based on its validation trades so far. Its trades stay exactly as they are; this only changes what you see next, and TraderAlign will keep tracking whether its real performance improves or worsens.'
        : 'Enter Main Workflow with this strategy? Your validation trades stay exactly as they are; this only changes what you see next, and cannot be undone.';
    if (!confirm(confirmMsg)) return;
    btn.disabled = true;
    btn.textContent = 'Entering Main Workflow…';
    var errBox = document.getElementById('graduate-error');
    errBox.style.display = 'none';
    fetch('/traderalign/api/validation/graduate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ strategy_id: strategyId, force: !!force })
    })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (data.success) {
                window.location.href = '/traderalign/strategy?graduated_from=' + encodeURIComponent(strategyId);
            } else if (data.warning && !force) {
                // Edge status changed since page load (e.g. a trade closed
                // in another tab) — offer the same override inline instead
                // of a dead-end error.
                if (confirm('This strategy still has not demonstrated a profitable edge. Continue anyway?')) {
                    graduateStrategy(strategyId, btn, true);
                    return;
                }
                btn.disabled = false;
                btn.textContent = defaultLabel;
            } else {
                errBox.textContent = data.error || 'Graduation failed.';
                errBox.style.display = 'block';
                btn.disabled = false;
                btn.textContent = defaultLabel;
            }
        })
        .catch(function() {
            errBox.textContent = 'Graduation failed: network error. Please try again.';
            errBox.style.display = 'block';
            btn.disabled = false;
            btn.textContent = defaultLabel;
        });
}
</script>

<!-- Trade Screenshots modal — shared markup/JS/CSS with public/journal.php,
     see assets/js/trade-screenshots.js and assets/css/trade-screenshots.css.
     Restored 2026-08-18 as its own feature, separate from "View Trade" (not
     present on this page's own trade list, untouched everywhere it exists). -->
<div id="rn-screenshot-modal-backdrop" class="rn-screenshot-modal-backdrop" style="display:none" onclick="if(event.target===this) rnCloseScreenshotModal()">
    <div class="rn-screenshot-modal-panel">
        <div class="rn-screenshot-modal-head">
            <h3>Trade Screenshots</h3>
            <button type="button" class="rn-screenshot-modal-close" onclick="rnCloseScreenshotModal()">✕ Close</button>
        </div>
        <div id="rn-screenshot-modal-error" class="rn-screenshot-modal-error" style="display:none"></div>
        <div id="rn-screenshot-modal-body"></div>
        <label class="rn-screenshot-modal-label" for="rn-screenshot-modal-file">Upload a screenshot (from TradingView or elsewhere)</label>
        <input type="file" id="rn-screenshot-modal-file" class="rn-screenshot-modal-file" accept="image/jpeg,image/png,image/gif,image/webp">
        <div class="rn-screenshot-modal-actions">
            <button type="button" class="rn-screenshot-cancel-btn" onclick="rnCloseScreenshotModal()">Close</button>
            <button type="button" class="rn-screenshot-upload-btn" id="rn-screenshot-upload-btn" onclick="rnUploadScreenshot()">Upload</button>
        </div>
    </div>
</div>

</main>
</body>
</html>
