<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../src/ScopedDb.php';
require_once __DIR__ . '/../src/Auth.php';
require_once __DIR__ . '/../src/Csrf.php';

if (session_status() === PHP_SESSION_NONE) {
    session_name(SESSION_NAME); 
    session_start(); 
}

try {
    $dsn = "mysql:host=" . DB_HOST . ";port=" . DB_PORT . ";dbname=" . DB_NAME . ";charset=utf8mb4";
    $pdo = new PDO($dsn, DB_USER, DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, 
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, 
        PDO::ATTR_EMULATE_PREPARES => false
    ]);
} catch (PDOException $e) { 
    header('Location: /traderalign/dashboard?error=Server+error'); 
    exit; 
}

$auth = new Auth($pdo);
$userId = $auth->requireAuth();
$db = new ScopedDb($pdo, $userId);

$message = '';
$error = '';

// ── RESUME HANDLER — must run before any HTML output (2026-08-17) ──────
// "Validate a New Edge →" used to always create a brand-new strategy, even
// for a trader who already had one in progress — real gap flagged in the
// workflow-isolation-leakage pass, closed here. A GET with
// ?resume=<strategy_id> re-enters the validation workflow for an EXISTING
// validation strategy instead of creating anything new: no strategy
// insert, no strategy_versions row, no checklist_items — just the same
// enterValidation() flip returnToMain()'s counterpart already uses
// (src/ValidationService.php), then straight to Validation Tracker for
// that exact strategy. Ownership + is_validation=1 checked server-side —
// a foreign or already-graduated strategy id falls through to the normal
// page with an error, never silently "succeeds" on the wrong row.
if ($_SERVER['REQUEST_METHOD'] === 'GET' && !empty($_GET['resume'])) {
    $resumeId = $_GET['resume'];
    $resumeRows = $db->raw(
        "SELECT id FROM strategies WHERE id = :sid AND user_id = :uid AND is_validation = 1 AND is_active = 1 AND deleted_at IS NULL",
        [':sid' => $resumeId, ':uid' => $userId]
    );
    if (!empty($resumeRows)) {
        ValidationService::enterValidation($userId, $db);
        header('Location: /traderalign/journal-validation?strategy=' . urlencode($resumeId));
        exit;
    }
    $error = 'That validation strategy could not be found.';
}

// Existing validation strategies — shown as a "Resume" choice above the
// create-new form below so this page is never the ONLY way back into a
// strategy the trader already started elsewhere (via "← Back to Main
// Workflow", or simply revisiting this page). Fetched regardless of the
// user's current workflow_state — a main-workflow user who parked a
// validation strategy mid-progress needs to see it here just as much as
// someone already validating.
$existingValidationStrategies = ValidationService::getValidationStrategies($userId, $db);

// ── READ-ONLY VIEW MODE (2026-08-20) ────────────────────────────────────
// Validation Workflow's own equivalent of strategy.php's
// ?strategy_id=X&mode=readonly viewer — public/strategies.php's "Forgot
// strategy?" link previously always pointed at /traderalign/strategy
// regardless of workflow, which is main-workflow-only
// (ValidationService::gateMainWorkflowOnly()) and silently redirected a
// validating user to Validation Tracker instead, a real, reported
// dead-end unrelated to "I forgot my strategy." Same URL shape as
// strategy.php's own readonly mode (?mode=readonly&strategy_id=X&
// back_account_id=Y) so both pages' "Forgot strategy?" links are built the
// same way from public/strategies.php. Ownership + is_validation=1 are
// verified server-side, same as the resume handler above — a foreign or
// non-validation strategy id falls through to the normal create-form page
// rather than silently rendering someone else's data.
$readonlyMode = ($_GET['mode'] ?? '') === 'readonly' && !empty($_GET['strategy_id']);
$readonlyStrategy = null;
$readonlyItemsByCategory = [];
$readonlyBackAccountId = $_GET['back_account_id'] ?? null;
$readonlyBackUrl = '/traderalign/strategies' . ($readonlyBackAccountId ? ('?account_id=' . urlencode($readonlyBackAccountId)) : '');
// The exact same $_POST-shaped array the real create form already reads
// every field from (name/market/trading_style/timeframes[]/instruments[]/
// description/notes/target_win_rate/risk_reward_objective/
// personal_hypotheses/market_conditions/trading_rules) — built from what
// the trader actually saved, never invented. When set, $_POST itself is
// overwritten with this further down (readonly GET only — real POST
// submissions are unaffected, mutually exclusive by construction) so the
// unmodified form markup below renders pre-filled with zero changes to
// its own HTML: every field already does `$_POST['x'] ?? ''`.
$readonlyPrefill = null;
if ($readonlyMode) {
    $rsRows = $db->raw(
        "SELECT s.id, s.name, s.description, s.trading_style, sv.id AS version_id,
                sv.instruments_traded, sv.session_preference, sv.max_risk_per_trade_pct,
                sv.backtested_win_rate, sv.backtested_avg_rr
         FROM strategies s
         JOIN strategy_versions sv ON sv.id = s.current_version_id
         WHERE s.id = :sid AND s.user_id = :uid AND s.is_validation = 1 AND s.deleted_at IS NULL",
        [':sid' => $_GET['strategy_id'], ':uid' => $userId]
    );
    if (!empty($rsRows)) {
        $readonlyStrategy = $rsRows[0];
        $riItems = $db->raw(
            "SELECT category, raw_text, polished_text, verification_hint, is_required
             FROM checklist_items WHERE strategy_version_id = :vid
             ORDER BY FIELD(category, 'setup', 'entry', 'risk', 'execution'), position",
            [':vid' => $readonlyStrategy['version_id']]
        );
        foreach ($riItems as $ri) {
            $readonlyItemsByCategory[$ri['category']][] = $ri;
        }

        // market/notes/target_win_rate/risk_reward_objective/personal_
        // hypotheses/market_conditions/trading_rules were never given real
        // strategy_versions columns (see the POST handler below) — the
        // ONLY place the trader's real original answers survive is the
        // 'validation_projects' entry this same POST handler appends to
        // user_profiles.onboarding_context, keyed by strategy_id. Most
        // recent matching entry wins (an array append, so "most recent" is
        // simply the last match) in case this strategy was ever
        // resubmitted. Missing entirely (a strategy predating this
        // metadata, or a lookup failure) means these five fields are
        // genuinely unknown and stay blank — never guessed.
        $roProfile = $db->selectById('user_profiles', $userId, 'user_id');
        $roContext = json_decode($roProfile['onboarding_context'] ?? '{}', true) ?: [];
        $roProjectData = [];
        foreach (($roContext['validation_projects'] ?? []) as $roProject) {
            if (($roProject['strategy_id'] ?? null) === $readonlyStrategy['id']) {
                $roProjectData = $roProject['data'] ?? [];
            }
        }

        $roDescription = $readonlyStrategy['description'];
        // The POST handler falls back to the literal string 'Validation
        // strategy' when the trader left this blank — treat that exact
        // fallback as "was blank," never show it as if the trader typed it.
        if ($roDescription === 'Validation strategy') { $roDescription = ''; }

        $readonlyPrefill = [
            'name' => $readonlyStrategy['name'],
            'market' => $roProjectData['market'] ?? '',
            'trading_style' => $readonlyStrategy['trading_style'],
            'timeframes' => json_decode($readonlyStrategy['session_preference'] ?? '[]', true) ?: [],
            'instruments' => json_decode($readonlyStrategy['instruments_traded'] ?? '[]', true) ?: [],
            'description' => $roDescription,
            'notes' => $roProjectData['notes'] ?? '',
            'max_risk_per_trade_pct' => $readonlyStrategy['max_risk_per_trade_pct'] !== null
                ? rtrim(rtrim(number_format((float)$readonlyStrategy['max_risk_per_trade_pct'], 2), '0'), '.')
                : '',
            'target_win_rate' => $readonlyStrategy['backtested_win_rate'] !== null
                ? rtrim(rtrim(number_format((float)$readonlyStrategy['backtested_win_rate'], 2), '0'), '.')
                : ($roProjectData['target_win_rate'] ?? ''),
            'risk_reward_objective' => !empty($roProjectData['risk_reward_objective'])
                ? $roProjectData['risk_reward_objective']
                : ($readonlyStrategy['backtested_avg_rr'] !== null ? '1:' . rtrim(rtrim(number_format((float)$readonlyStrategy['backtested_avg_rr'], 2), '0'), '.') : ''),
            'personal_hypotheses' => $roProjectData['personal_hypotheses'] ?? '',
            'market_conditions' => $roProjectData['market_conditions'] ?? '',
            'trading_rules' => $roProjectData['trading_rules_not_captured'] ?? '',
        ];
    } else {
        $readonlyMode = false;
        $error = 'That validation strategy could not be found.';
    }
}
if ($readonlyPrefill !== null) {
    // Deliberate, controlled override — the real create form below reads
    // every field from $_POST, so feeding it the trader's own saved
    // answers here is what makes the SAME, unmodified form render already
    // filled in. Only ever reached via GET (readonly mode never coexists
    // with the POST handler above, which already checked !$readonlyMode
    // before this point), so a real form submission is never affected.
    $_POST = $readonlyPrefill;
}

// ── POST HANDLER — must run before any HTML output ─────────────────────
if (!$readonlyMode && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $market = $_POST['market'] ?? '';
    $tradingStyle = $_POST['trading_style'] ?? 'day_trader';
    $timeframes = $_POST['timeframes'] ?? [];
    $instruments = $_POST['instruments'] ?? [];
    $description = trim($_POST['description'] ?? '');
    $notes = trim($_POST['notes'] ?? '');
    $checklistItems = json_decode($_POST['checklist_items'] ?? '[]', true) ?: [];
    
    // Additional fields
    $targetWinRate = !empty($_POST['target_win_rate']) ? (float)$_POST['target_win_rate'] : null;
    $riskRewardObjective = trim($_POST['risk_reward_objective'] ?? '');
    $personalHypotheses = trim($_POST['personal_hypotheses'] ?? '');
    $marketConditions = trim($_POST['market_conditions'] ?? '');
    $tradingRulesNotCaptured = trim($_POST['trading_rules'] ?? '');

    // 2026-08-20: real gap closed — max_risk_per_trade_pct was previously
    // hardcoded to 1 regardless of any input; backtested_win_rate/
    // backtested_avg_rr were never written to strategy_versions at all
    // (target_win_rate/risk_reward_objective were only ever stored inside
    // user_profiles.onboarding_context's JSON blob, never in the real
    // columns public/strategies.php's shared checklist page reads to
    // render the Risk/Avg R:R/Win Rate stat chips). This is the direct
    // cause of a validation strategy's checklist page looking sparser than
    // a main-workflow one — same shared template, less real data behind
    // it. Fixed at the source rather than faking anything: these three
    // fields now write to the real columns when the trader fills them in,
    // same as strategy.php's own builder already does; still fully
    // optional, still null when left blank (main.php never fabricates a
    // number, and this page shouldn't either).
    $maxRiskPct = is_numeric($_POST['max_risk_per_trade_pct'] ?? null) ? (float)$_POST['max_risk_per_trade_pct'] : 1.0;
    if ($maxRiskPct <= 0 || $maxRiskPct > 10) { $maxRiskPct = 1.0; }
    $backtestedAvgRr = null;
    if ($riskRewardObjective !== '' && preg_match('/(\d+(?:\.\d+)?)\s*:\s*(\d+(?:\.\d+)?)/', $riskRewardObjective, $rrMatch)) {
        // "1:2" / "1 : 2.5" style free text — the second number is the
        // reward side of a risk-of-1 ratio, same meaning as strategy.php's
        // own "Avg Reward per $1 Risked" field.
        $riskSide = (float)$rrMatch[1];
        $rewardSide = (float)$rrMatch[2];
        if ($riskSide > 0) { $backtestedAvgRr = round($rewardSide / $riskSide, 2); }
    } elseif ($riskRewardObjective !== '' && is_numeric($riskRewardObjective)) {
        $backtestedAvgRr = (float)$riskRewardObjective;
    }
    
    // Validation
    if (empty($name)) {
        $error = 'Strategy name is required.';
    } elseif (empty($market)) {
        $error = 'Please select a market.';
    } elseif (empty($timeframes) || !is_array($timeframes)) {
        $error = 'Please select at least one timeframe.';
    } elseif (empty($instruments) || !is_array($instruments)) {
        $error = 'Please select at least one instrument.';
    } else {
        try {
            $pdo->beginTransaction();
            
            // Insert strategy with is_validation = 1
            $strategyId = $db->insert('strategies', [
                'name' => $name,
                'description' => $description ?: 'Validation strategy',
                'trading_style' => $tradingStyle,
                'is_active' => 1,
                'is_validation' => 1,
            ]);
            
            // Create strategy version
            $versionId = $db->insert('strategy_versions', [
                'strategy_id' => $strategyId,
                'version_number' => 1,
                'instruments_traded' => json_encode($instruments),
                'session_preference' => json_encode($timeframes),
                'max_risk_per_trade_pct' => $maxRiskPct,
                'max_losing_streak' => 3,
                'backtested_win_rate' => $targetWinRate,
                'backtested_avg_rr' => $backtestedAvgRr,
                'polished_by' => 'manual',
            ]);
            
            // Update strategy with current version
            $stmt = $pdo->prepare('UPDATE strategies SET current_version_id = :vid WHERE id = :sid AND user_id = :uid');
            $stmt->execute([':vid' => $versionId, ':sid' => $strategyId, ':uid' => $userId]);
            
            // Insert checklist items
            $categoryOrder = ['setup' => 0, 'entry' => 1, 'risk' => 2, 'execution' => 3];
            foreach ($checklistItems as $item) {
                $db->insert('checklist_items', [
                    'strategy_version_id' => $versionId,
                    'category' => $item['category'] ?? 'setup',
                    'position' => $item['position'] ?? 0,
                    'raw_text' => $item['text'] ?? '',
                    'polished_text' => $item['text'] ?? '',
                    // 2026-08-20: previously always hardcoded to '' — the
                    // form now collects an optional "how would you verify
                    // this" hint per item (same real fields.php's own
                    // checklist builder already reads), so a validation
                    // strategy's items can carry the same explanatory
                    // detail a main-workflow strategy's do once the trader
                    // fills it in.
                    'verification_hint' => trim((string)($item['hint'] ?? '')),
                    'is_required' => 1,
                ]);
            }
            
            // Store additional validation data
            $validationData = [
                'market' => $market,
                'timeframes' => $timeframes,
                'instruments' => $instruments,
                'notes' => $notes,
                'target_win_rate' => $targetWinRate,
                'risk_reward_objective' => $riskRewardObjective,
                'personal_hypotheses' => $personalHypotheses,
                'market_conditions' => $marketConditions,
                'trading_rules_not_captured' => $tradingRulesNotCaptured,
            ];
            
            $profile = $db->selectById('user_profiles', $userId, 'user_id');
            $existingContext = json_decode($profile['onboarding_context'] ?? '{}', true) ?: [];
            $existingContext['validation_projects'][] = [
                'strategy_id' => $strategyId,
                'data' => $validationData,
                'created_at' => date('Y-m-d H:i:s')
            ];
            
            // 2026-08-12 edge-warning pass: this form is now reachable from
            // TWO places — onboarding's "Developing a Trading Edge" path
            // (already sets workflow_state='validation' itself, via
            // onboarding-stage3.php, before a user ever reaches here) and a
            // sidebar/Dashboard entry point visible to main-workflow users
            // who want to test a fresh candidate strategy (see "Validate a
            // New Edge →" on public/dashboard.php). For that second case,
            // workflow_state is still 'main' at this point — flip it here,
            // atomically with the strategy insert, so the whole app
            // (sidebar, Reports/Strategy gates, Dashboard) immediately
            // treats this user as validating. A no-op (still just
            // 'validation') for the onboarding-originated case.
            //
            // 2026-08-16 workflow-isolation-leakage pass: this is also the
            // ONLY place validation_entry_source gets set to
            // 'main_workflow' — recorded here, atomically with the flip
            // itself, so ValidationService::getEntrySource()/sidebar.php's
            // "← Back to Main Workflow" link can tell this case apart from
            // an onboarding-originated validation session (which must never
            // show that link — see onboarding-stage3.php). Only written
            // when this branch is actually the one doing the flip (i.e. the
            // workflow_state !== 'validation' check below) — the onboarding
            // case already set its own 'onboarding' value and must not be
            // overwritten by re-visiting this form while already validating.
            $profileForFlip = $db->selectById('user_profiles', $userId, 'user_id');
            $updatePayload = ['onboarding_context' => json_encode($existingContext)];
            if (($profileForFlip['workflow_state'] ?? 'main') !== 'validation') {
                $updatePayload['workflow_state'] = 'validation';
                $updatePayload['validation_entry_source'] = 'main_workflow';
            }
            $db->update('user_profiles', $userId, $updatePayload, 'user_id');

            $pdo->commit();
            
            $redirectUrl = '/traderalign/journal-validation?strategy=' . $strategyId;
            echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0;url=' . $redirectUrl . '"></head><body><script>window.location.href="' . $redirectUrl . '";</script></body></html>';
            exit;
            
        } catch (\Throwable $e) {
            $pdo->rollBack();
            $error = 'Failed to save: ' . $e->getMessage();
        }
    }
}

// Instrument database
$instrumentsByCategory = [
    'forex' => [
        ['symbol' => 'EURUSD', 'name' => 'EUR/USD', 'type' => 'Major'],
        ['symbol' => 'GBPUSD', 'name' => 'GBP/USD', 'type' => 'Major'],
        ['symbol' => 'USDJPY', 'name' => 'USD/JPY', 'type' => 'Major'],
        ['symbol' => 'AUDUSD', 'name' => 'AUD/USD', 'type' => 'Major'],
        ['symbol' => 'NZDUSD', 'name' => 'NZD/USD', 'type' => 'Major'],
        ['symbol' => 'USDCAD', 'name' => 'USD/CAD', 'type' => 'Major'],
        ['symbol' => 'USDCHF', 'name' => 'USD/CHF', 'type' => 'Major'],
        ['symbol' => 'EURGBP', 'name' => 'EUR/GBP', 'type' => 'Cross'],
        ['symbol' => 'EURJPY', 'name' => 'EUR/JPY', 'type' => 'Cross'],
        ['symbol' => 'GBPJPY', 'name' => 'GBP/JPY', 'type' => 'Cross'],
        ['symbol' => 'AUDJPY', 'name' => 'AUD/JPY', 'type' => 'Cross'],
        ['symbol' => 'NZDJPY', 'name' => 'NZD/JPY', 'type' => 'Cross'],
        ['symbol' => 'EURCHF', 'name' => 'EUR/CHF', 'type' => 'Cross'],
        ['symbol' => 'GBPCHF', 'name' => 'GBP/CHF', 'type' => 'Cross'],
        ['symbol' => 'AUDCAD', 'name' => 'AUD/CAD', 'type' => 'Cross'],
        ['symbol' => 'EURAUD', 'name' => 'EUR/AUD', 'type' => 'Cross'],
        ['symbol' => 'GBPAUD', 'name' => 'GBP/AUD', 'type' => 'Cross'],
        ['symbol' => 'AUDNZD', 'name' => 'AUD/NZD', 'type' => 'Cross'],
    ],
    'indices' => [
        ['symbol' => 'US30', 'name' => 'Dow Jones 30', 'type' => 'US Index'],
        ['symbol' => 'US500', 'name' => 'S&P 500', 'type' => 'US Index'],
        ['symbol' => 'US100', 'name' => 'NASDAQ 100', 'type' => 'US Index'],
        ['symbol' => 'UK100', 'name' => 'FTSE 100', 'type' => 'European Index'],
        ['symbol' => 'GER40', 'name' => 'DAX 40', 'type' => 'European Index'],
        ['symbol' => 'AUS200', 'name' => 'ASX 200', 'type' => 'Asia-Pacific Index'],
        ['symbol' => 'JPN225', 'name' => 'Nikkei 225', 'type' => 'Asia-Pacific Index'],
        ['symbol' => 'EU50', 'name' => 'Euro Stoxx 50', 'type' => 'European Index'],
    ],
    'commodities' => [
        ['symbol' => 'XAUUSD', 'name' => 'Gold', 'type' => 'Precious Metal'],
        ['symbol' => 'XAGUSD', 'name' => 'Silver', 'type' => 'Precious Metal'],
        ['symbol' => 'XPTUSD', 'name' => 'Platinum', 'type' => 'Precious Metal'],
        ['symbol' => 'XPDUSD', 'name' => 'Palladium', 'type' => 'Precious Metal'],
        ['symbol' => 'USOIL', 'name' => 'US Crude Oil', 'type' => 'Energy'],
        ['symbol' => 'UKOIL', 'name' => 'Brent Crude Oil', 'type' => 'Energy'],
        ['symbol' => 'NATGAS', 'name' => 'Natural Gas', 'type' => 'Energy'],
        ['symbol' => 'COFFEE', 'name' => 'Coffee', 'type' => 'Soft Commodity'],
        ['symbol' => 'COCOA', 'name' => 'Cocoa', 'type' => 'Soft Commodity'],
        ['symbol' => 'SUGAR', 'name' => 'Sugar', 'type' => 'Soft Commodity'],
        ['symbol' => 'CORN', 'name' => 'Corn', 'type' => 'Agricultural'],
        ['symbol' => 'WHEAT', 'name' => 'Wheat', 'type' => 'Agricultural'],
        ['symbol' => 'COTTON', 'name' => 'Cotton', 'type' => 'Soft Commodity'],
    ],
    'crypto' => [
        ['symbol' => 'BTCUSD', 'name' => 'Bitcoin', 'type' => 'Major Crypto'],
        ['symbol' => 'ETHUSD', 'name' => 'Ethereum', 'type' => 'Major Crypto'],
        ['symbol' => 'XRPUSD', 'name' => 'Ripple', 'type' => 'Altcoin'],
        ['symbol' => 'SOLUSD', 'name' => 'Solana', 'type' => 'Altcoin'],
        ['symbol' => 'ADAUSD', 'name' => 'Cardano', 'type' => 'Altcoin'],
        ['symbol' => 'DOTUSD', 'name' => 'Polkadot', 'type' => 'Altcoin'],
        ['symbol' => 'BNBUSD', 'name' => 'Binance Coin', 'type' => 'Exchange Token'],
        ['symbol' => 'LTCUSD', 'name' => 'Litecoin', 'type' => 'Altcoin'],
    ],
    'stocks' => [
        ['symbol' => 'AAPL', 'name' => 'Apple Inc.', 'type' => 'Technology'],
        ['symbol' => 'MSFT', 'name' => 'Microsoft Corp.', 'type' => 'Technology'],
        ['symbol' => 'GOOGL', 'name' => 'Alphabet Inc.', 'type' => 'Technology'],
        ['symbol' => 'AMZN', 'name' => 'Amazon.com Inc.', 'type' => 'Consumer'],
        ['symbol' => 'NVDA', 'name' => 'NVIDIA Corp.', 'type' => 'Technology'],
        ['symbol' => 'META', 'name' => 'Meta Platforms', 'type' => 'Technology'],
        ['symbol' => 'TSLA', 'name' => 'Tesla Inc.', 'type' => 'Automotive'],
        ['symbol' => 'JPM', 'name' => 'JPMorgan Chase', 'type' => 'Financial'],
        ['symbol' => 'BAC', 'name' => 'Bank of America', 'type' => 'Financial'],
        ['symbol' => 'WMT', 'name' => 'Walmart Inc.', 'type' => 'Retail'],
        ['symbol' => 'JNJ', 'name' => 'Johnson & Johnson', 'type' => 'Healthcare'],
        ['symbol' => 'PFE', 'name' => 'Pfizer Inc.', 'type' => 'Healthcare'],
    ],
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Strategy Validation - 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">
<style>
.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}
body{background:var(--background);margin:0;font-family:var(--font-sans)}

.validation-container{max-width:720px;margin:0 auto;padding:0 0 40px 0}
.page-header{margin-bottom:32px}
.page-header h1{font-size:1.8rem;font-weight:700;color:var(--foreground);margin-bottom:8px;letter-spacing:-.01em}
.page-header p{color:var(--foreground-dim);font-size:0.9rem;line-height:1.5}

.form-card{background:var(--background-elevated);border:1px solid var(--border);border-radius:var(--radius-xl);padding:28px 32px;margin-bottom:20px;position:relative;overflow:hidden}
.form-card::after{content:'';position:absolute;top:0;right:0;width:200px;height:200px;background:radial-gradient(circle,color-mix(in srgb,var(--primary) 3%,transparent),transparent 70%);pointer-events:none}
.form-card>*{position:relative;z-index:1}
.form-card h2{font-size:1.1rem;font-weight:700;color:var(--foreground);margin-bottom:6px}
.form-card .card-subtitle{font-size:12px;color:var(--foreground-dim);margin-bottom:20px}

.field{margin-bottom:18px}
.field label{display:block;font-size:10px;text-transform:uppercase;letter-spacing:.7px;color:var(--foreground-dim);margin-bottom:4px;font-weight:600}
.field label.required::after{content:' *';color:var(--negative);font-weight:700}
.field input,.field select,.field textarea{font-family:var(--font-sans);font-size:13px;color:var(--foreground);background:var(--background-surface);border:1px solid var(--border);border-radius:var(--radius-sm);padding:9px 11px;width:100%;outline:none;transition:border-color .15s}
.field input:focus,.field select:focus,.field textarea:focus{border-color:var(--ring);box-shadow:0 0 0 3px color-mix(in srgb,var(--ring) 15%,transparent)}
.field textarea{resize:vertical;min-height:80px}
.field .err{color:var(--destructive);font-size:10px;margin-top:3px;display:none}
.field.invalid input,.field.invalid select{border-color:var(--destructive)}
.field.invalid .err{display:block}

.timeframe-picker{display:flex;flex-wrap:wrap;gap:6px;margin-top:6px}
.tf-pick{padding:6px 12px;border-radius:var(--radius-full);font-size:11px;font-weight:500;color:var(--foreground-dim);border:1px solid var(--border);background:none;cursor:pointer;transition:all .15s;font-family:var(--font-mono)}
.tf-pick:hover{color:var(--foreground);border-color:var(--primary)}
.tf-pick.selected{background:color-mix(in srgb,var(--primary) 15%,transparent);color:var(--primary);border-color:var(--primary)}

.instrument-section{margin-top:20px}
.instrument-search{position:relative;margin-top:8px}
.instrument-search input{width:100%;padding:9px 12px;font-size:13px;background:var(--background-surface);border:1px solid var(--border);border-radius:var(--radius-sm);color:var(--foreground);font-family:var(--font-sans);outline:none;transition:border-color .15s}
.instrument-search input:focus{border-color:var(--ring);box-shadow:0 0 0 3px color-mix(in srgb,var(--ring) 15%,transparent)}
.instrument-dropdown{position:absolute;top:100%;left:0;right:0;background:var(--popover);border:1px solid var(--border);border-radius:var(--radius-sm);max-height:240px;overflow:auto;z-index:20;display:none;box-shadow:0 8px 24px rgba(0,0,0,.3);margin-top:4px}
.instrument-dropdown.show{display:block}
.instrument-option{padding:8px 12px;cursor:pointer;display:flex;align-items:center;justify-content:space-between;color:var(--foreground);transition:background .12s;border-bottom:1px solid color-mix(in srgb,var(--border) 30%,transparent);font-size:13px}
.instrument-option:last-child{border-bottom:none}
.instrument-option:hover,.instrument-option.highlighted{background:color-mix(in srgb,var(--primary) 10%,transparent)}
.instrument-option .inst-type{font-size:10px;color:var(--foreground-dim);text-transform:uppercase;background:var(--background-surface);padding:2px 6px;border-radius:var(--radius-full)}
.selected-instruments{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}
.inst-chip{display:inline-flex;align-items:center;gap:4px;padding:4px 10px;border-radius:var(--radius-full);font-size:11px;background:color-mix(in srgb,var(--primary) 15%,transparent);color:var(--primary);border:1px solid color-mix(in srgb,var(--primary) 25%,transparent);font-family:var(--font-mono)}
.inst-chip .remove{cursor:pointer;opacity:.5;font-weight:700;font-size:12px}
.inst-chip .remove:hover{opacity:1}
.no-instruments{font-size:12px;color:var(--foreground-dim);opacity:.6;font-style:italic;padding:8px 0}
.instrument-count{font-size:11px;color:var(--foreground-dim);margin-top:4px}

.g2{display:grid;grid-template-columns:1fr 1fr;gap:14px}
.g3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px}

/* Checklist builder — matches strategy.php cat-row pattern */
.cat-row{background:var(--background-surface);border:1px solid var(--border);border-radius:var(--radius-lg);padding:16px 18px;margin-bottom:10px;transition:border-color .2s ease}
.cat-row:hover{border-color:color-mix(in srgb,var(--primary) 20%,transparent)}
.cat-row .cr-head{display:flex;align-items:center;gap:10px;margin-bottom:8px}
.cat-row .cr-badge{font-size:10px;text-transform:uppercase;letter-spacing:.8px;font-weight:700;padding:3px 9px;border-radius:var(--radius-full);flex-shrink:0}
.cat-setup{background:color-mix(in srgb,var(--primary) 18%,transparent);color:var(--primary)}
.cat-entry{background:color-mix(in srgb,var(--positive) 18%,transparent);color:var(--positive)}
.cat-risk{background:color-mix(in srgb,var(--warning) 18%,transparent);color:var(--warning)}
.cat-execution{background:color-mix(in srgb,#a78bfa 18%,transparent);color:#a78bfa}
.cat-row .cr-items{display:flex;flex-direction:column;gap:5px}
.cat-row .ci-row{display:flex;gap:8px;align-items:flex-start}
.cat-row .ci-row-main{flex:1;padding:7px 9px;background:var(--background);border:1px solid var(--border);border-radius:var(--radius-sm);display:flex;flex-direction:column;gap:3px;min-width:0}
.cat-row .ci-row-text{font-size:12px;color:var(--foreground);font-family:var(--font-sans)}
/* Verification hint — same "how would you confirm this" concept as
   strategy.php's own checklist builder, shown once saved so a validation
   strategy's items carry the same explanatory detail a main-workflow
   strategy's do (2026-08-20, real gap: this field was previously never
   collected at all, always saved empty). */
.cat-row .ci-row-hint{font-size:10.5px;color:var(--foreground-dim);font-style:italic;line-height:1.4;display:flex;align-items:flex-start;gap:4px}
.cat-row .ci-x{color:var(--foreground-dim);cursor:pointer;font-size:14px;padding:7px 5px;background:none;border:none;line-height:1;font-family:var(--font-sans);flex-shrink:0}
.cat-row .ci-x:hover{color:var(--destructive)}
.cat-row .cr-add{font-size:11px;color:var(--primary);margin-top:6px;font-weight:600;background:none;border:none;cursor:pointer;font-family:var(--font-sans)}
.cat-row .cr-add-form{display:none;margin-top:8px;flex-direction:column;gap:6px}
.cat-row .cr-add-form.show{display:flex}
.cat-row .cr-add-form input{font-size:12px;padding:7px 9px;background:var(--background);border:1px solid var(--border);border-radius:var(--radius-sm);color:var(--foreground);font-family:var(--font-sans);outline:none;width:100%;box-sizing:border-box}
.cat-row .cr-add-form input:focus{border-color:var(--ring)}
.cat-row .cr-add-form input.hint-input{font-style:italic;color:var(--foreground-muted)}
.cat-row .cr-add-actions{display:flex;gap:6px}
.btn-add-save{font-size:11px;font-weight:600;padding:7px 12px;border-radius:var(--radius-sm);background:var(--primary);color:#fff;border:none;cursor:pointer;font-family:var(--font-sans);white-space:nowrap}
.btn-add-cancel{font-size:11px;font-weight:500;padding:7px 10px;border-radius:var(--radius-sm);background:transparent;color:var(--foreground-dim);border:1px solid var(--border);cursor:pointer;font-family:var(--font-sans);white-space:nowrap}
.cat-empty{font-size:11px;color:var(--foreground-dim);opacity:.6;padding:6px 0;font-style:italic;line-height:1.5}

.expand-toggle{display:flex;align-items:center;gap:8px;font-size:13px;font-weight:600;color:var(--foreground-dim);cursor:pointer;background:none;border:none;font-family:var(--font-sans);padding:8px 0;transition:color .15s;user-select:none}
.expand-toggle:hover{color:var(--foreground)}
.expand-toggle .arrow{display:inline-block;transition:transform .2s ease;font-size:10px}
.expand-toggle.open .arrow{transform:rotate(90deg)}
.expand-content{display:none;padding-top:12px}
.expand-content.show{display:block}

.save-bar{display:flex;align-items:center;justify-content:flex-end;gap:12px;margin-top:24px}
.btn-revert{display:inline-flex;align-items:center;gap:6px;padding:10px 18px;border-radius:var(--radius-lg);font-size:13px;font-weight:500;color:var(--foreground-dim);background:var(--background-surface);border:1px solid var(--border);cursor:pointer;transition:all .2s ease;font-family:var(--font-sans);text-decoration:none}
.btn-revert:hover{color:var(--foreground);border-color:var(--foreground-dim);background:var(--background-elevated)}
.btn-save{display:inline-flex;align-items:center;gap:8px;padding:10px 22px;border-radius:var(--radius-lg);font-size:13px;font-weight:600;color:#fff;background:var(--primary);border:1px solid var(--primary);cursor:pointer;transition:all .2s ease;font-family:var(--font-sans);box-shadow:0 2px 8px color-mix(in srgb,var(--primary) 30%,transparent)}
.btn-save:hover{opacity:.9;transform:translateY(-1px)}
.btn-save:active{transform:translateY(0)}

.alert{background:var(--background-surface);border:1px solid var(--border);border-radius:var(--radius-md);padding:12px 16px;margin-bottom:20px;font-size:13px}
.alert.error{border-color:color-mix(in srgb,var(--negative) 30%,transparent);color:var(--negative);background:color-mix(in srgb,var(--negative) 5%,transparent)}
.alert.success{border-color:color-mix(in srgb,var(--positive) 30%,transparent);color:var(--positive);background:color-mix(in srgb,var(--positive) 5%,transparent)}

/* Resume Existing Validation — 2026-08-17. Same form-card shell as the
   create-new sections below, distinguished by a primary-colored top accent
   (::after removed since form-card already reserves that spot) so it reads
   as the recommended first choice when it's present, not just another card. */
.resume-card{border-top:2px solid var(--primary)}
.resume-card h2{display:flex;align-items:center;gap:8px}
.resume-list{display:flex;flex-direction:column;gap:10px;margin-top:14px}
.resume-row{display:flex;align-items:center;justify-content:space-between;gap:14px;background:var(--background-surface);border:1px solid var(--border);border-radius:var(--radius-lg);padding:14px 16px;flex-wrap:wrap}
.resume-row-info{min-width:0}
.resume-row-name{font-size:14px;font-weight:700;color:var(--foreground)}
.resume-row-meta{font-size:11px;color:var(--foreground-dim);margin-top:3px}
.resume-row .btn-save{white-space:nowrap;text-decoration:none}
.new-validation-heading{font-size:11px;text-transform:uppercase;letter-spacing:.7px;color:var(--foreground-dim);font-weight:700;margin:28px 0 -8px}

@media(max-width:768px){
  .g2{grid-template-columns:1fr}
  .g3{grid-template-columns:1fr}
  .form-card{padding:20px 18px}
  .main{padding:1rem}
}
</style>
</head>
<body class="dash-layout">

<?php require __DIR__ . '/sidebar.php'; ?>

<main class="main">

<div class="validation-container">

  <?php if ($readonlyMode): ?>
  <!-- Read-only viewer (2026-08-20) — reached from Strategies' "Forgot
       strategy?" link. Per explicit direction: show the REAL create form,
       exactly as-is, filled with exactly what the trader actually saved
       (via the $_POST override above) — not a redesigned summary. The
       <form> below is byte-identical to the create-form path; only the
       $_POST source and the surrounding <fieldset disabled> (added right
       before/after the <form> tag further down) differ in this mode. -->
  <a href="<?= htmlspecialchars($readonlyBackUrl) ?>" class="btn-revert" style="text-decoration:none;display:inline-flex;align-items:center;gap:6px;margin-bottom:18px">← Back</a>

  <div class="page-header">
    <h1>🔬 Strategy Validation</h1>
    <p>Read-only, exactly as you saved it.</p>
  </div>

  <?php else: ?>

  <div class="page-header">
    <h1>🔬 Strategy Validation</h1>
    <p>Document the strategy you're developing for systematic validation. Select your market to see relevant instruments.</p>
  </div>

  <?php endif; /* end $readonlyMode header if/else — the <form> below is
                  shared by both modes, reached unconditionally either way */ ?>

  <?php if (!$readonlyMode): ?>
  <?php if (!empty($existingValidationStrategies)): ?>
  <!-- Resume Existing Validation (2026-08-17) — a strategy already in
       progress is never re-created; picking it here just re-enters the
       validation workflow for the exact same strategy/trades. -->
  <div class="form-card resume-card">
    <h2>🔄 Resume Existing Validation</h2>
    <p class="card-subtitle">You already have <?= count($existingValidationStrategies) === 1 ? 'a validation strategy' : count($existingValidationStrategies) . ' validation strategies' ?> in progress. Continue where you left off, or start a brand-new one below.</p>
    <div class="resume-list">
      <?php foreach ($existingValidationStrategies as $evs):
          $evsProgress = ValidationService::getProgress($userId, $evs['version_id'], $db);
      ?>
      <div class="resume-row">
        <div class="resume-row-info">
          <div class="resume-row-name"><?= htmlspecialchars($evs['name']) ?></div>
          <div class="resume-row-meta"><?= $evsProgress['trade_count'] ?> of <?= $evsProgress['target'] ?> validation trades<?= $evsProgress['at_cap'] ? ' (at the ' . $evsProgress['max'] . '-trade cap)' : '' ?></div>
        </div>
        <a class="btn-save" href="/traderalign/strategy-validation?resume=<?= urlencode($evs['id']) ?>">Continue Validating →</a>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
  <div class="new-validation-heading">Or start a new validation strategy</div>
  <?php endif; ?>

  <?php if ($error): ?>
    <div class="alert error"><?= htmlspecialchars($error) ?></div>
  <?php endif; ?>

  <?php if ($message): ?>
    <div class="alert success"><?= htmlspecialchars($message) ?></div>
  <?php endif; ?>
  <?php endif; /* !$readonlyMode */ ?>

  <?php if ($readonlyMode): ?><fieldset disabled style="border:none;padding:0;margin:0;min-width:0"><?php endif; ?>
  <form method="POST" action="/traderalign/strategy-validation" id="validation-form">
    <?= Csrf::field() ?>

    <!-- Core Fields -->
    <div class="form-card">
      <h2>📋 Core Strategy Details</h2>
      <p class="card-subtitle">Define the basic parameters of the strategy you want to validate.</p>
      
      <div class="field">
        <label class="required" for="name">Strategy Name</label>
        <input type="text" id="name" name="name" value="<?= htmlspecialchars($_POST['name'] ?? '') ?>" 
               placeholder="e.g. London Breakout, Asian Range Fade" maxlength="100" required>
        <div class="err">Strategy name is required.</div>
      </div>
      
      <div class="g2">
        <div class="field">
          <label class="required" for="market">Market</label>
          <select id="market" name="market" required onchange="onMarketChange()">
            <option value="">Select market…</option>
            <option value="forex" <?= ($_POST['market'] ?? '') === 'forex' ? 'selected' : '' ?>>Forex</option>
            <option value="indices" <?= ($_POST['market'] ?? '') === 'indices' ? 'selected' : '' ?>>Indices</option>
            <option value="commodities" <?= ($_POST['market'] ?? '') === 'commodities' ? 'selected' : '' ?>>Commodities</option>
            <option value="crypto" <?= ($_POST['market'] ?? '') === 'crypto' ? 'selected' : '' ?>>Crypto</option>
            <option value="stocks" <?= ($_POST['market'] ?? '') === 'stocks' ? 'selected' : '' ?>>Stocks</option>
          </select>
          <div class="err">Please select a market.</div>
        </div>
        
        <div class="field">
          <label class="required" for="trading_style">Trading Style</label>
          <select id="trading_style" name="trading_style" required>
            <option value="day_trader" <?= ($_POST['trading_style'] ?? '') === 'day_trader' ? 'selected' : '' ?>>Day Trader</option>
            <option value="swing" <?= ($_POST['trading_style'] ?? '') === 'swing' ? 'selected' : '' ?>>Swing Trader</option>
            <option value="scalper" <?= ($_POST['trading_style'] ?? '') === 'scalper' ? 'selected' : '' ?>>Scalper</option>
            <option value="position" <?= ($_POST['trading_style'] ?? '') === 'position' ? 'selected' : '' ?>>Position Trader</option>
          </select>
        </div>
      </div>
      
      <div class="field">
        <label class="required">Timeframes</label>
        <div class="timeframe-picker" id="timeframe-picker">
          <?php
          $allTimeframes = timeframeOptions();
          $selectedTimeframes = $_POST['timeframes'] ?? [];
          foreach ($allTimeframes as $tf):
              $isSelected = in_array($tf, $selectedTimeframes);
          ?>
            <button type="button" class="tf-pick <?= $isSelected ? 'selected' : '' ?>" 
                    data-value="<?= $tf ?>" onclick="toggleTimeframe(this)">
              <?= $tf ?>
            </button>
          <?php endforeach; ?>
        </div>
        <div class="err" id="timeframe-error">Please select at least one timeframe.</div>
      </div>
      
      <div class="instrument-section" id="instrument-section">
        <div class="field">
          <label class="required">Instruments <span style="font-weight:400;text-transform:none;opacity:.6">(select market first)</span></label>
          <div class="instrument-search" id="instrument-search-wrapper">
            <input type="text" id="instrument-search-input" 
                   placeholder="Search instruments…" 
                   oninput="filterInstruments(this.value)" 
                   onkeydown="handleInstrumentKey(event)"
                   autocomplete="off"
                   disabled>
            <div class="instrument-dropdown" id="instrument-dropdown"></div>
          </div>
          <div class="selected-instruments" id="selected-instruments">
            <?php if (empty($_POST['market'])): ?>
              <div class="no-instruments">Select a market to see available instruments</div>
            <?php endif; ?>
          </div>
          <div class="instrument-count" id="instrument-count"></div>
          <div class="err" id="instrument-error">Please select at least one instrument.</div>
        </div>
      </div>
      
      <div class="field">
        <label for="description">Short Description</label>
        <textarea id="description" name="description" rows="3" 
                  placeholder="Brief description of the strategy and what edge you're trying to validate…"><?= htmlspecialchars($_POST['description'] ?? '') ?></textarea>
      </div>
      
      <div class="field">
        <label for="notes">Notes</label>
        <textarea id="notes" name="notes" rows="4" 
                  placeholder="Any additional notes, observations, or context about this strategy…"><?= htmlspecialchars($_POST['notes'] ?? '') ?></textarea>
      </div>
    </div>
    
    <!-- Checklist Builder -->
    <div class="form-card">
      <h2>✅ Pre-Trade Checklist</h2>
      <p class="card-subtitle">Define the checks you'll perform before every trade. These items help you stay disciplined.</p>
      <input type="hidden" name="checklist_items" id="checklist-items-input" value="">
      
      <div id="checklist-container">
        <?php
        $categories = [
            'setup'     => ['label' => 'Setup',     'class' => 'cat-setup',     'default' => 'Trend agrees with direction'],
            'entry'     => ['label' => 'Entry',     'class' => 'cat-entry',     'default' => 'Entry at planned zone'],
            'risk'      => ['label' => 'Risk',      'class' => 'cat-risk',      'default' => 'Risk stays at or under 1%'],
            'execution' => ['label' => 'Execution', 'class' => 'cat-execution', 'default' => 'Reward is at least 2x the risk'],
        ];
        foreach ($categories as $catKey => $catInfo):
        ?>
        <div class="cat-row" data-category="<?= $catKey ?>">
          <div class="cr-head">
            <span class="cr-badge <?= $catInfo['class'] ?>"><?= $catInfo['label'] ?></span>
          </div>
          <div class="cr-items" id="items-<?= $catKey ?>"></div>
          <button type="button" class="cr-add" onclick="showAddForm('<?= $catKey ?>')">+ Add item</button>
          <div class="cr-add-form" id="add-form-<?= $catKey ?>">
            <input type="text" id="add-input-<?= $catKey ?>" placeholder="What must be true?" onkeydown="if(event.key==='Enter'){document.getElementById('add-hint-<?= $catKey ?>').focus();event.preventDefault();}">
            <input type="text" id="add-hint-<?= $catKey ?>" class="hint-input" placeholder="Optional: how would you verify this? (a hint for yourself later)" onkeydown="if(event.key==='Enter'){saveChecklistItem('<?= $catKey ?>');event.preventDefault();}">
            <div class="cr-add-actions">
              <button type="button" class="btn-add-save" onclick="saveChecklistItem('<?= $catKey ?>')">Save</button>
              <button type="button" class="btn-add-cancel" onclick="hideAddForm('<?= $catKey ?>')">Cancel</button>
            </div>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    
    <!-- Expandable Additional Information -->
    <div class="form-card">
      <button type="button" class="expand-toggle" onclick="toggleExpand(this)" id="expand-toggle">
        <span class="arrow">▶</span> Additional Information
      </button>
      <p class="card-subtitle" style="margin-top:4px">Optional details that help track your validation process more precisely.</p>
      
      <div class="expand-content" id="expand-content">
        <div class="g3">
          <div class="field">
            <label for="max_risk_per_trade_pct">Max Risk Per Trade %</label>
            <input type="number" id="max_risk_per_trade_pct" name="max_risk_per_trade_pct"
                   value="<?= htmlspecialchars($_POST['max_risk_per_trade_pct'] ?? '') ?>"
                   placeholder="1" min="0.01" max="10" step="0.01">
          </div>

          <div class="field">
            <label for="target_win_rate">Target Win Rate %</label>
            <input type="number" id="target_win_rate" name="target_win_rate"
                   value="<?= htmlspecialchars($_POST['target_win_rate'] ?? '') ?>"
                   placeholder="e.g. 60" min="0" max="100" step="0.1">
          </div>

          <div class="field">
            <label for="risk_reward_objective">Risk-to-Reward Objective</label>
            <input type="text" id="risk_reward_objective" name="risk_reward_objective"
                   value="<?= htmlspecialchars($_POST['risk_reward_objective'] ?? '') ?>"
                   placeholder="e.g. 1:2, 1:3">
          </div>
        </div>

        <div class="field">
          <label for="personal_hypotheses">Personal Hypotheses</label>
          <textarea id="personal_hypotheses" name="personal_hypotheses" rows="3" 
                    placeholder="What are your hypotheses about this strategy? What do you expect to happen?"><?= htmlspecialchars($_POST['personal_hypotheses'] ?? '') ?></textarea>
        </div>
        
        <div class="field">
          <label for="market_conditions">Market Conditions</label>
          <textarea id="market_conditions" name="market_conditions" rows="3" 
                    placeholder="What market conditions does this strategy perform best in? (trending, ranging, news events, etc.)"><?= htmlspecialchars($_POST['market_conditions'] ?? '') ?></textarea>
        </div>
        
        <div class="field">
          <label for="trading_rules">Trading Rules Not Captured Elsewhere</label>
          <textarea id="trading_rules" name="trading_rules" rows="3" 
                    placeholder="Any additional rules or constraints for this strategy…"><?= htmlspecialchars($_POST['trading_rules'] ?? '') ?></textarea>
        </div>
      </div>
    </div>
    
    <?php if (!$readonlyMode): ?>
    <div class="save-bar">
      <a href="/traderalign/dashboard" class="btn-revert">Cancel</a>
      <button type="submit" class="btn-save">💾 Save & Continue to Journal</button>
    </div>
    <?php endif; ?>

  </form>
  <?php if ($readonlyMode): ?></fieldset><?php endif; ?>

</div>

</main>

<script>
const READONLY_MODE = <?= json_encode($readonlyMode) ?>;

// ── Instruments ────────────────────────────────────────
const instrumentsByCategory = <?= json_encode($instrumentsByCategory) ?>;
let selectedInstruments = <?= json_encode($_POST['instruments'] ?? []) ?>;
let instrumentHighlightIndex = -1;
let filteredInstruments = [];

// ── Checklist state ────────────────────────────────────
<?php if ($readonlyMode): ?>
// Read-only mode: the trader's own real, saved items (exactly what they
// added when they built this strategy) — never the create-form's starter
// defaults, which readonly mode never shows at all.
const checklistData = <?= json_encode(array_map(
    fn($catItems) => array_map(fn($it) => [
        'text' => $it['polished_text'] ?: $it['raw_text'],
        'hint' => $it['verification_hint'] ?: '',
    ], $catItems),
    array_merge(['setup' => [], 'entry' => [], 'risk' => [], 'execution' => []], $readonlyItemsByCategory)
)) ?>;
<?php else: ?>
// 2026-08-20: real gap closed — these 4 starter items previously had no
// hint at all and the Risk/Execution pair used raw math symbols (Risk ≤
// 1% / Reward ≥ 2x Risk) instead of plain language, so a trader who never
// customized past the defaults ended up with a checklist that looked
// noticeably sparser than a main-workflow strategy's, even after the
// per-item hint field was added. Same shared strategies.php render either
// way, edit or delete these like any other item.
const checklistData = {
    setup:     [{ text: 'Trend agrees with direction', hint: 'The higher-timeframe trend supports the direction you are about to trade.' }],
    entry:     [{ text: 'Entry at planned zone', hint: 'Price is trading inside the zone you identified beforehand, not being chased.' }],
    risk:      [{ text: 'Risk stays at or under 1%', hint: 'Position size keeps this trade risking at or below your declared limit.' }],
    execution: [{ text: 'Reward is at least 2x the risk', hint: 'The planned take-profit is at least twice as far away as the stop-loss.' }],
};
<?php endif; ?>

function renderChecklist() {
    Object.keys(checklistData).forEach(cat => {
        const container = document.getElementById('items-' + cat);
        const items = checklistData[cat];
        if (items.length === 0) {
            container.innerHTML = '<div class="cat-empty">No items yet, add your first check</div>';
        } else {
            container.innerHTML = items.map((item, i) => `
                <div class="ci-row">
                    <div class="ci-row-main">
                        <span class="ci-row-text">${escapeHtml(item.text)}</span>
                        ${item.hint ? `<span class="ci-row-hint">💡 ${escapeHtml(item.hint)}</span>` : ''}
                    </div>
                    <button type="button" class="ci-x" onclick="deleteChecklistItem('${cat}', ${i})" title="Remove">✕</button>
                </div>
            `).join('');
        }
    });
    updateChecklistHiddenInput();
}

function escapeHtml(str) {
    const div = document.createElement('div');
    div.textContent = str;
    return div.innerHTML;
}

function showAddForm(cat) {
    document.getElementById('add-form-' + cat).classList.add('show');
    document.getElementById('add-input-' + cat).focus();
}

function hideAddForm(cat) {
    document.getElementById('add-form-' + cat).classList.remove('show');
    document.getElementById('add-input-' + cat).value = '';
    document.getElementById('add-hint-' + cat).value = '';
}

function saveChecklistItem(cat) {
    const input = document.getElementById('add-input-' + cat);
    const hintInput = document.getElementById('add-hint-' + cat);
    const text = input.value.trim();
    const hint = hintInput.value.trim();
    if (!text) return;

    checklistData[cat].push({ text: text, hint: hint });
    input.value = '';
    hintInput.value = '';
    hideAddForm(cat);
    renderChecklist();
}

function deleteChecklistItem(cat, index) {
    checklistData[cat].splice(index, 1);
    renderChecklist();
}

function updateChecklistHiddenInput() {
    const allItems = [];
    Object.keys(checklistData).forEach(cat => {
        checklistData[cat].forEach((item, i) => {
            allItems.push({
                category: cat,
                position: i,
                text: item.text,
                hint: item.hint || '',
            });
        });
    });
    document.getElementById('checklist-items-input').value = JSON.stringify(allItems);
}

// ── Market change handler ──────────────────────────────
function onMarketChange() {
    const market = document.getElementById('market').value;
    const searchInput = document.getElementById('instrument-search-input');
    const dropdown = document.getElementById('instrument-dropdown');
    const selectedContainer = document.getElementById('selected-instruments');
    
    selectedInstruments = [];
    updateSelectedDisplay();
    updateHiddenInputs();
    
    if (market) {
        searchInput.disabled = false;
        searchInput.placeholder = 'Search ' + market + ' instruments…';
        searchInput.value = '';
        dropdown.innerHTML = '';
        dropdown.classList.remove('show');
        selectedContainer.innerHTML = '';
    } else {
        searchInput.disabled = true;
        searchInput.placeholder = 'Select a market to see available instruments';
        searchInput.value = '';
        dropdown.innerHTML = '';
        dropdown.classList.remove('show');
        selectedContainer.innerHTML = '<div class="no-instruments">Select a market to see available instruments</div>';
    }
    
    updateInstrumentCount();
}

function filterInstruments(query) {
    const market = document.getElementById('market').value;
    const dropdown = document.getElementById('instrument-dropdown');
    
    if (!market) { dropdown.classList.remove('show'); return; }
    
    const instruments = instrumentsByCategory[market] || [];
    
    if (!query.trim()) {
        filteredInstruments = instruments;
    } else {
        const searchTerm = query.toLowerCase();
        filteredInstruments = instruments.filter(inst => 
            inst.symbol.toLowerCase().includes(searchTerm) || 
            inst.name.toLowerCase().includes(searchTerm) ||
            inst.type.toLowerCase().includes(searchTerm)
        );
    }
    
    instrumentHighlightIndex = -1;
    
    if (filteredInstruments.length === 0) {
        dropdown.innerHTML = '<div class="instrument-option" style="color:var(--foreground-dim);cursor:default">No instruments found</div>';
    } else {
        dropdown.innerHTML = filteredInstruments.map((inst, index) => {
            const isSelected = selectedInstruments.includes(inst.symbol);
            return `<div class="instrument-option ${isSelected ? 'highlighted' : ''}" data-symbol="${inst.symbol}" data-index="${index}">
                <span><strong style="font-family:var(--font-mono)">${inst.symbol}</strong><span style="margin-left:8px;font-size:12px;opacity:.7">${inst.name}</span></span>
                <span class="inst-type">${inst.type}</span></div>`;
        }).join('');
    }
    
    dropdown.classList.add('show');
}

function handleInstrumentKey(event) {
    if (!filteredInstruments.length) return;
    if (event.key === 'ArrowDown') { instrumentHighlightIndex = Math.min(instrumentHighlightIndex + 1, filteredInstruments.length - 1); event.preventDefault(); updateHighlight(); }
    else if (event.key === 'ArrowUp') { instrumentHighlightIndex = Math.max(instrumentHighlightIndex - 1, 0); event.preventDefault(); updateHighlight(); }
    else if (event.key === 'Enter') { if (instrumentHighlightIndex >= 0 && filteredInstruments[instrumentHighlightIndex]) { toggleInstrument(filteredInstruments[instrumentHighlightIndex].symbol); } event.preventDefault(); }
    else if (event.key === 'Escape') { document.getElementById('instrument-dropdown').classList.remove('show'); document.getElementById('instrument-search-input').blur(); }
}

function updateHighlight() {
    document.querySelectorAll('#instrument-dropdown .instrument-option').forEach((opt, i) => opt.classList.toggle('highlighted', i === instrumentHighlightIndex));
}

function toggleInstrument(symbol) {
    const index = selectedInstruments.indexOf(symbol);
    if (index > -1) { selectedInstruments.splice(index, 1); } else { selectedInstruments.push(symbol); }
    updateSelectedDisplay();
    updateHiddenInputs();
    updateDropdownHighlights();
}

function updateDropdownHighlights() {
    document.querySelectorAll('#instrument-dropdown .instrument-option').forEach(opt => {
        const symbol = opt.dataset.symbol;
        if (symbol && selectedInstruments.includes(symbol)) { opt.classList.add('highlighted'); } else { opt.classList.remove('highlighted'); }
    });
}

function updateSelectedDisplay() {
    const container = document.getElementById('selected-instruments');
    const market = document.getElementById('market').value;
    if (!market) { container.innerHTML = '<div class="no-instruments">Select a market to see available instruments</div>'; return; }
    if (selectedInstruments.length === 0) { container.innerHTML = '<div class="no-instruments">No instruments selected. Search and click to add.</div>'; }
    else { container.innerHTML = selectedInstruments.map(s => `<span class="inst-chip">${s}<span class="remove" onclick="toggleInstrument('${s}')">×</span></span>`).join(''); }
    updateInstrumentCount();
}

function updateInstrumentCount() {
    const el = document.getElementById('instrument-count');
    el.textContent = selectedInstruments.length > 0 ? `${selectedInstruments.length} instrument${selectedInstruments.length > 1 ? 's' : ''} selected` : '';
}

function updateHiddenInputs() {
    document.querySelectorAll('.instrument-hidden-input').forEach(el => el.remove());
    const form = document.getElementById('validation-form');
    selectedInstruments.forEach(symbol => {
        const input = document.createElement('input'); input.type = 'hidden'; input.name = 'instruments[]'; input.value = symbol; input.className = 'instrument-hidden-input'; form.appendChild(input);
    });
}

// ── Timeframe selection ────────────────────────────────
function toggleTimeframe(button) { button.classList.toggle('selected'); updateHiddenTimeframes(); }
function updateHiddenTimeframes() {
    const selected = document.querySelectorAll('.tf-pick.selected');
    document.querySelectorAll('.timeframe-hidden-input').forEach(el => el.remove());
    const container = document.getElementById('validation-form');
    Array.from(selected).forEach(el => {
        const input = document.createElement('input'); input.type = 'hidden'; input.name = 'timeframes[]'; input.value = el.dataset.value; input.className = 'timeframe-hidden-input'; container.appendChild(input);
    });
}

// ── Expand/collapse ────────────────────────────────────
function toggleExpand(button) {
    const content = document.getElementById('expand-content');
    const isOpen = content.classList.contains('show');
    if (isOpen) { content.classList.remove('show'); button.classList.remove('open'); }
    else { content.classList.add('show'); button.classList.add('open'); }
}

// ── Form validation ────────────────────────────────────
document.getElementById('validation-form').addEventListener('submit', function(e) {
    let valid = true;
    
    const nameInput = document.getElementById('name');
    const nameField = nameInput.closest('.field');
    if (!nameInput.value.trim()) { nameField.classList.add('invalid'); valid = false; } else { nameField.classList.remove('invalid'); }
    
    const marketSelect = document.getElementById('market');
    const marketField = marketSelect.closest('.field');
    if (!marketSelect.value) { marketField.classList.add('invalid'); valid = false; } else { marketField.classList.remove('invalid'); }
    
    const selectedTimeframes = document.querySelectorAll('.tf-pick.selected');
    const timeframeError = document.getElementById('timeframe-error');
    if (selectedTimeframes.length === 0) { timeframeError.style.display = 'block'; valid = false; } else { timeframeError.style.display = 'none'; }
    
    const instrumentError = document.getElementById('instrument-error');
    if (selectedInstruments.length === 0) { instrumentError.style.display = 'block'; valid = false; } else { instrumentError.style.display = 'none'; }
    
    if (!valid) { e.preventDefault(); return; }
    
    updateChecklistHiddenInput();
});

// ── Event Delegation: instrument dropdown clicks ───────
document.getElementById('instrument-dropdown').addEventListener('click', function(e) {
    const option = e.target.closest('.instrument-option');
    if (option && option.dataset.symbol) { toggleInstrument(option.dataset.symbol); }
});

// Close dropdown when clicking outside
document.addEventListener('click', function(e) {
    const searchWrapper = document.getElementById('instrument-search-wrapper');
    const dropdown = document.getElementById('instrument-dropdown');
    if (searchWrapper && !searchWrapper.contains(e.target)) { dropdown.classList.remove('show'); }
});

// ── Initialize ─────────────────────────────────────────
document.addEventListener('DOMContentLoaded', function() {
    renderChecklist();
    updateHiddenTimeframes();
    updateHiddenInputs();
    
    const market = document.getElementById('market').value;
    // The <fieldset disabled> wrapper (readonly mode only, see the PHP
    // above) locks every descendant form control natively — except this
    // one, which the create-form's own init logic explicitly re-enables
    // whenever a market is set (needed for real creation, always true
    // here too since a saved strategy always has one). Guarded so readonly
    // mode stays genuinely locked instead of leaving one live text input.
    if (market) { if (!READONLY_MODE) { document.getElementById('instrument-search-input').disabled = false; } updateSelectedDisplay(); }
    
    const additionalFields = ['target_win_rate', 'risk_reward_objective', 'personal_hypotheses', 'market_conditions', 'trading_rules'];
    if (additionalFields.some(id => { const el = document.getElementById(id); return el && el.value.trim(); })) {
        document.getElementById('expand-content').classList.add('show');
        document.getElementById('expand-toggle').classList.add('open');
    }
});
</script>

</body>
</html>