<?php
/**
 * Strategies — strategy selection + pre-trade checklist.
 *
 * Replaces public/checklist.php (deleted 2026-08-01) as the second step of
 * the redesigned workflow:
 *
 *   Trading Center (account selection) → Strategies (strategy + checklist)
 *   → Calculator (execution)
 *
 * This page deliberately owns NOTHING about accounts — no account selector,
 * no account summary, no stage/rules card, no Add Account. Those all now
 * live exclusively in Trading Center (public/trading-center.php). This page
 * only ever reads the account that was already chosen there, via
 * ?account_id= (Trading Center's own "Continue to Strategies" link) or the
 * same $_SESSION['active_account_id'] key public/checklist.php used to set
 * — reused as-is for continuity, not reinvented.
 *
 * The strategy picker (search / first-5-most-recently-used / Show More) is
 * src/StrategyPicker.php — a dedicated render function, but the exact same
 * shared CSS/JS widget (assets/css/account-picker.css,
 * assets/js/account-picker.js) src/AccountPicker.php's own pickers use. See
 * that file's docblock for why a second render *function* is correct reuse
 * here, not a second implementation of the widget.
 *
 * "Forgot strategy?" no longer opens an in-page modal (the old carousel
 * modal in checklist.php is gone, not ported) — it navigates to
 * /traderalign/strategy?strategy_id=X&mode=readonly, a real read-only
 * viewer mode added to strategy.php this same session (see that file).
 *
 * The checklist grid/progress bar/gate bar were originally ported verbatim
 * from checklist.php (explicit instruction at the time not to redesign).
 * Session 2026-08-01 (visual polish pass, explicitly requested): the whole
 * page's CSS and supporting markup were reworked for visual polish — gradient
 * card surfaces, per-category accent color (--cat-color, driven by $catMeta
 * below) carried through the category header/left-border/checkbox/badge, a
 * shimmering progress fill, a blurred sticky gate bar, and quick strategy
 * stat chips (Risk/Avg R:R/Win Rate) in the selector row. Purely CSS/markup —
 * every id/class the JS reads (#prog/#pct/#reqCount/#items, .check-item,
 * .ticked, data-id/data-required, #warningModal/#modalTitle/#modalList, and
 * the .cat-setup/.cat-risk/.cat-execution/.cat-entry classes the warning
 * modal's proceed() builds client-side as `li-cat cat-<category>`) is
 * unchanged, and toggleItem()/updateStats()/proceed()/submitChecklist() were
 * not touched.
 */

$userId = $auth->requireAuth();
require_once __DIR__ . '/../src/StrategyPicker.php';

// ── Account context — read-only here, never selectable on this page ──────
// 2026-08-17 account-level workflow isolation: this direct-by-id lookup
// bypassed Trading Center's own (now-fixed) account-picker scoping
// entirely — a crafted/stale ?account_id= for a foreign-workflow account
// (or one simply left over in $_SESSION['active_account_id'] from before a
// workflow switch) would have rendered that account's real label/balance/
// lifecycle here even though it could never have been reached through the
// picker itself. Scoped the same way as everywhere else, via
// trading_accounts.workflow_context.
$requestedAccountId = $_GET['account_id'] ?? null;
$spWorkflowState = ValidationService::getWorkflowState($userId, $db);
// 2026-08-18 persistence fix: $_SESSION alone never survives logout, a new
// browser session, or a new day — Kevin's own report. trading_accounts.
// strategies_selected_at (stamped by apRecordStrategiesSelection(), fired
// ONLY from this page's own explicit ?account_id= arrival) is the real,
// database-backed memory of "the account this user is actually trading";
// it's the third link in the chain, only consulted when neither an explicit
// URL param nor the current PHP session already has an answer.
// apLastStrategiesAccountId() is already scoped to $spWorkflowState, so it
// can never resolve to an account from the other workflow.
//
// 2026-08-20 correction: previously read apLastSelectedAccountId() — the
// SAME pointer Trading Center's own Account Home stamps on every plain
// view (correct for Quick Access's "recently viewed" ordering, wrong for
// this). That meant merely browsing a different account's balance in
// Trading Center — no intent to switch what's being traded — silently
// changed which account Strategies resolved to after a later logout/login.
// See migration_add_strategies_selection_pointer.sql for the full account.
$candidateAccountId = $requestedAccountId
    ?: ($_SESSION['active_account_id'] ?? null)
    ?: apLastStrategiesAccountId($userId, $db, $spWorkflowState);

$account = null;
if ($candidateAccountId) {
    $rows = $db->raw(
        "SELECT ta.id, ta.label, ta.account_type, ta.lifecycle_state AS personal_lifecycle_state,
                ta.prop_firm_name, ta.current_balance,
                ca.id AS challenge_account_id, ca.challenge_type, ca.current_stage,
                ca.lifecycle_state, ca.rules, ca.custom_rules
         FROM trading_accounts ta
         LEFT JOIN challenge_accounts ca ON ca.account_id = ta.id AND ca.deleted_at IS NULL
         WHERE ta.id = :id AND ta.user_id = :uid AND ta.workflow_context = :wfctx AND ta.deleted_at IS NULL",
        [':id' => $candidateAccountId, ':uid' => $userId, ':wfctx' => $spWorkflowState]
    );
    $account = $rows[0] ?? null;
}
if ($account) {
    $_SESSION['active_account_id'] = $account['id'];
    // Only stamp on a real, explicit URL-driven selection (a link click —
    // from Trading Center's "Continue to Strategies →", or any future deep
    // link) — never merely because the session/DB fallback silently carried
    // an existing selection forward. Keeps strategies_selected_at meaning
    // exactly what it says: the moment this account was actually chosen to
    // trade, not every page view.
    if ($requestedAccountId) {
        apRecordStrategiesSelection($userId, $account['id'], $db);
    }
} elseif ($candidateAccountId) {
    // Had something to try and it didn't resolve — don't keep retrying a dead id.
    unset($_SESSION['active_account_id']);
}

$isPropFirm = $account && $account['account_type'] === 'prop_firm';
$isPersonal = $account && $account['account_type'] === 'personal';
$isCompletedPhase = $isPropFirm && in_array($account['lifecycle_state'] ?? '', ['phase_1_complete', 'phase_2_complete', 'phase_3_complete'], true);

$lifecycleStateLabels = [
    'phase_1_active'    => 'Phase 1 Active',
    'phase_1_complete'  => 'Phase 1 Complete',
    'phase_2_active'    => 'Phase 2 Active',
    'phase_2_complete'  => 'Phase 2 Complete',
    'phase_3_active'    => 'Phase 3 Active',
    'phase_3_complete'  => 'Phase 3 Complete',
    'funded_active'     => 'Funded Active',
    'breached'          => 'Breached',
    'closed'            => 'Closed',
    'archived'          => 'Archived',
    'active'            => 'Active',
];
$accountStatusLabel = '';
if ($account) {
    $accountStatusLabel = $isPropFirm
        ? ($lifecycleStateLabels[$account['lifecycle_state']] ?? ucfirst(str_replace('_', ' ', (string)$account['lifecycle_state'])))
        : ($lifecycleStateLabels[$account['personal_lifecycle_state'] ?? 'active'] ?? 'Active');
}

// ── Strategies ─────────────────────────────────────────────────────────
// Always fetched (not gated on $account) — this page has two real modes:
//   1. With an account context: strategy selection + checklist (trade prep).
//   2. Without one (reached via Trading Center's own "Strategies" tile):
//      a plain strategy SWITCHER — picking a strategy here jumps straight
//      into Dashboard with it active, and Dashboard's own existing JS
//      (sessionStorage 'active_strategy_id') plus sidebar.php's existing
//      propagation script then carry that same strategy onto Reports and
//      Drafts automatically — the same mechanism those three pages already
//      shared before this redesign, just given a real, discoverable entry
//      point instead of requiring a strategy_id to already be in the URL.
// Validation Workflow: while the user's active workflow is 'validation',
// this page's picker/checklist must only ever expose their validation
// strategy(ies) — spFetchValidationStrategies() (src/StrategyPicker.php),
// the same row shape as spFetchStrategies() so the shared picker widget
// below needs no change either way. Falls back to /strategy-validation
// (not /strategy) when the validating user has no validation strategy yet.
$workflowState = ValidationService::getWorkflowState($userId, $db);
$isValidatingWorkflow = $workflowState === 'validation';
$allStrategies = $isValidatingWorkflow
    ? spFetchValidationStrategies($userId, $db)
    : spFetchStrategies($userId, $db);
$strategy = null;
$version = null;
$items = [];
$itemsData = [];
$selectedId = null;

if (empty($allStrategies)) {
    header('Location: ' . ($isValidatingWorkflow ? '/traderalign/strategy-validation' : '/traderalign/strategy'));
    exit;
}

if ($account) {
    // 2026-08-18 clarification: Validation Workflow only ever has ONE active
    // strategy (spFetchValidationStrategies() above already returns just
    // that), so it is always the selected one — never resolved from
    // $_GET['strategy_id']/$_SESSION, which is Main Workflow's multi-
    // strategy selection/history mechanism and must not apply here. This
    // guarantees the validation strategy stays "selected" across logout, a
    // new session, or a new day, since it's re-derived fresh from the
    // strategies table on every request rather than remembered anywhere.
    if ($isValidatingWorkflow) {
        $selectedId = $allStrategies[0]['id'];
    } else {
        // 2026-08-20: carry the active strategy forward through the whole
        // workflow (Calculator, Save, Drafts, everywhere else). Real bug
        // reported directly. Only a genuinely explicit ?strategy_id=
        // arrival (a real click on the picker below, or "Proceed to
        // Calculator" having already been reached via one) is recorded as
        // the new system-wide active strategy, via spRecordActiveStrategy()
        // (src/StrategyPicker.php), never a silent session/default
        // fallback. Matches apRecordStrategiesSelection()'s own "only
        // stamp on real, explicit selection" philosophy for accounts.
        $requestedStrategyId = $_GET['strategy_id'] ?? null;
        $selectedId = $requestedStrategyId ?? ($_SESSION['strategies_strategy_id'] ?? null);
        $validSelected = null;
        foreach ($allStrategies as $s) {
            if ($s['id'] === $selectedId) { $validSelected = $s; break; }
        }
        if (!$validSelected) { $validSelected = $allStrategies[0]; }
        $selectedId = $validSelected['id'];
        if ($requestedStrategyId !== null && $requestedStrategyId === $selectedId) {
            spRecordActiveStrategy($userId, $selectedId, $db, $workflowState);
        } else {
            $_SESSION['strategies_strategy_id'] = $selectedId;
        }
    }

    $strategy = $db->selectById('strategies', $selectedId);
    $version = $db->selectById('strategy_versions', $strategy['current_version_id']);
    if (!$version) {
        $vrows = $db->raw("SELECT * FROM strategy_versions WHERE strategy_id = :sid ORDER BY version_number DESC LIMIT 1", [':sid' => $strategy['id']]);
        $version = $vrows[0] ?? null;
    }

    if ($version) {
        // Category order matches the canonical checklist-builder order used
        // by BOTH strategy.php's CATEGORIES constant and strategy-validation.php's
        // $categories array (setup, entry, risk, execution) — this display
        // query previously used a different order (setup, risk, execution,
        // entry), so a checklist rendered here before taking a trade could
        // show its categories in a different sequence than the trader built
        // them in, in either workflow (this file is the one shared renderer
        // for both). Real, pre-existing inconsistency, fixed here rather than
        // in a second renderer.
        $items = $db->select('checklist_items', "strategy_version_id = :svid", [':svid' => $version['id']], '*', "FIELD(category, 'setup', 'entry', 'risk', 'execution'), position");
    }

    $itemsData = array_map(fn($i) => [
        'id' => $i['id'],
        'text' => $i['polished_text'] ?: $i['raw_text'],
        'is_required' => (bool)$i['is_required'],
        'category' => $i['category'],
    ], $items);
} else {
    // Analytics-switcher mode — best-effort highlight only, from the same
    // PHP session key the trade-prep mode above writes to (may or may not
    // match whatever's actually live in the browser's sessionStorage, which
    // PHP can't read — purely a nice-to-have, never load-bearing). Same
    // Validation exception as above: the one validation strategy is always
    // the highlighted one, never dependent on session state.
    $selectedId = $isValidatingWorkflow ? $allStrategies[0]['id'] : ($_SESSION['strategies_strategy_id'] ?? null);
}

// Category → icon/label/accent-color, purely presentational (drives the
// per-item --cat-color custom property and the category header/badge).
// Falls back gracefully for any category name outside the documented
// setup/risk/execution/entry enum rather than assuming it can't happen.
$catMeta = [
    'setup'     => ['icon' => '🧭', 'label' => 'Setup',     'color' => 'var(--primary)'],
    'risk'      => ['icon' => '⚠️', 'label' => 'Risk',       'color' => 'var(--warning)'],
    'execution' => ['icon' => '⚡', 'label' => 'Execution', 'color' => '#A78BFA'],
    'entry'     => ['icon' => '🎯', 'label' => 'Entry',      'color' => 'var(--positive)'],
];
function spCatMeta(array $catMeta, ?string $cat): array {
    return $catMeta[$cat] ?? ['icon' => '▪', 'label' => ucfirst((string)$cat), 'color' => 'var(--foreground-dim)'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Strategies - 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/account-picker.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}
body{background:var(--background);margin:0;background-image:radial-gradient(ellipse 1100px 560px at 10% -12%,color-mix(in srgb,var(--primary) 9%,transparent),transparent 62%),radial-gradient(ellipse 900px 520px at 105% 8%,color-mix(in srgb,var(--positive) 6%,transparent),transparent 60%);background-attachment:fixed}
.main{margin-left:4rem;flex:1;padding:2.5rem 2.5rem 7rem;max-width:1020px}

/* Header */
.back-link{font-size:.78rem;font-weight:600;color:var(--foreground-dim);margin-bottom:1.15rem;display:inline-flex;align-items:center;gap:.4rem;text-decoration:none;transition:all var(--t-fast);background:var(--background-elevated);border:1px solid var(--border);border-radius:var(--radius-full);padding:.35rem .85rem .35rem .6rem}
.back-link:hover{color:var(--primary);border-color:color-mix(in srgb,var(--primary) 40%,var(--border));transform:translateX(-2px)}
.page-head{display:flex;align-items:center;gap:.9rem;margin-bottom:.35rem}
.page-icon{width:2.6rem;height:2.6rem;flex-shrink:0;border-radius:var(--radius-lg);background:linear-gradient(155deg,color-mix(in srgb,var(--primary) 32%,var(--background-elevated)),var(--background-elevated));border:1px solid color-mix(in srgb,var(--primary) 35%,var(--border));display:flex;align-items:center;justify-content:center;font-size:1.25rem;box-shadow:0 4px 14px color-mix(in srgb,var(--primary) 20%,transparent)}
.page-title{font-size:1.65rem;font-weight:800;letter-spacing:-.02em;color:var(--foreground);line-height:1.15}
.page-sub{color:var(--foreground-muted);font-size:.9rem;margin:.5rem 0 1.75rem;line-height:1.55;max-width:58ch}

/* Strategy selector row — the ONE thing above the checklist */
.selector-row{display:flex;align-items:center;justify-content:space-between;gap:1rem;flex-wrap:wrap;margin-bottom:1.5rem;padding:1rem 1.25rem;background:linear-gradient(160deg,color-mix(in srgb,var(--primary) 5%,var(--background-elevated)),var(--background-elevated));border:1px solid var(--border);border-radius:var(--radius-xl);box-shadow:var(--shadow-md)}
.selector-row-left{display:flex;align-items:center;gap:1rem;flex-wrap:wrap}
/* The shared .rn-account-picker-panel (assets/css/account-picker.css) anchors
   right:0 by default — correct where it's used elsewhere (button sits at the
   right of its row, e.g. Trading Center/Journal), but on this page the
   strategy-picker button is the LEFTMOST thing on the row, so right:0 makes
   the panel expand leftward off the edge of the page, under the sidebar.
   Scoped override, page-local only — the shared component/CSS/JS itself is
   untouched, and every other page that uses it is unaffected. */
.selector-row .rn-account-picker-panel{right:auto;left:0}
.selector-row .rn-account-picker-btn{background:var(--background-surface)}
.strategy-stats{display:flex;gap:.5rem;flex-wrap:wrap}
.stat-chip{display:flex;align-items:baseline;gap:.35rem;background:var(--background-surface);border:1px solid var(--border);border-radius:var(--radius-md);padding:.4rem .7rem}
.stat-chip .sc-val{font-family:var(--font-mono);font-size:.85rem;font-weight:700;color:var(--foreground)}
.stat-chip .sc-lbl{font-size:.6rem;color:var(--foreground-dim);text-transform:uppercase;letter-spacing:.05em;font-weight:700}
.forgot-link{font-size:.78rem;font-weight:600;color:var(--foreground-dim);text-decoration:none;transition:all var(--t-fast);padding:.5rem .95rem;border-radius:var(--radius-md);border:1px solid var(--border);background:var(--background-surface);white-space:nowrap}
.forgot-link:hover{color:var(--primary);border-color:color-mix(in srgb,var(--primary) 40%,var(--border));background:color-mix(in srgb,var(--primary) 10%,var(--background-surface))}

.empty-state{text-align:center;padding:4.5rem 2rem;color:var(--foreground-dim);background:var(--background-elevated);border:1px dashed var(--border);border-radius:var(--radius-xl)}
.empty-state .es-icon{font-size:2.4rem;margin-bottom:.85rem;opacity:.85}

/* Progress */
.progress-card{background:linear-gradient(160deg,color-mix(in srgb,var(--positive) 7%,var(--background-elevated)),var(--background-elevated));border:1px solid var(--border);border-radius:var(--radius-xl);padding:1.1rem 1.35rem;display:flex;align-items:center;gap:1.1rem;margin-bottom:1.5rem;box-shadow:var(--shadow-md)}
.progress-card .prog-label{font-size:.7rem;font-weight:800;text-transform:uppercase;letter-spacing:.08em;color:var(--foreground-dim);white-space:nowrap;display:flex;align-items:center;gap:.4rem}
.progress-card .prog-bar{flex:1;height:9px;background:var(--background);border-radius:999px;overflow:hidden;box-shadow:inset 0 1px 3px rgba(0,0,0,.35)}
.progress-card .prog-fill{height:100%;width:0%;background:linear-gradient(90deg,color-mix(in srgb,var(--positive) 85%,black),var(--positive) 55%,#34d399);border-radius:999px;transition:width .5s cubic-bezier(.4,0,.2,1);position:relative;overflow:hidden}
.progress-card .prog-fill::after{content:'';position:absolute;inset:0;background:linear-gradient(90deg,transparent,rgba(255,255,255,.3),transparent);animation:prog-shimmer 2.4s ease-in-out infinite}
@keyframes prog-shimmer{0%{transform:translateX(-100%)}100%{transform:translateX(100%)}}
.progress-card .prog-pct{font-family:var(--font-mono);font-size:1.05rem;font-weight:800;color:var(--foreground);white-space:nowrap;min-width:44px;text-align:right}

/* Checklist Grid */
.checklist-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:.6rem;margin-bottom:1.75rem}
.cat-header{font-size:.68rem;font-weight:800;text-transform:uppercase;letter-spacing:.1em;color:var(--cat-color,var(--foreground-dim));padding:1.15rem .2rem .4rem;grid-column:1/-1;display:flex;align-items:center;gap:.5rem}
.cat-header:first-child{padding-top:0}
.cat-header .cat-header-icon{font-size:.85rem}
.cat-header::after{content:'';flex:1;height:1px;background:linear-gradient(90deg,color-mix(in srgb,var(--cat-color,var(--border)) 40%,var(--border)),transparent)}
.check-item{--cat-color:var(--foreground-dim);background:var(--background-elevated);border:1px solid var(--border);border-left:3px solid color-mix(in srgb,var(--cat-color) 42%,var(--border));border-radius:var(--radius-lg);padding:.9rem 1rem;cursor:pointer;transition:all .18s cubic-bezier(.4,0,.2,1);position:relative;overflow:hidden;user-select:none}
.check-item:hover{border-color:color-mix(in srgb,var(--cat-color) 48%,var(--border));border-left-color:var(--cat-color);transform:translateY(-2px);box-shadow:0 10px 22px -10px color-mix(in srgb,var(--cat-color) 55%,transparent)}
.check-item.ticked{background:color-mix(in srgb,var(--positive) 6%,var(--background-elevated));border-color:color-mix(in srgb,var(--positive) 30%,var(--border));border-left-color:var(--positive)}
.check-item.ticked:hover{box-shadow:0 10px 22px -10px color-mix(in srgb,var(--positive) 45%,transparent)}
.check-item .ci-top{display:flex;align-items:flex-start;gap:.7rem}
.check-box{width:21px;height:21px;border-radius:6px;border:2px solid color-mix(in srgb,var(--cat-color) 55%,var(--border));flex-shrink:0;display:flex;align-items:center;justify-content:center;transition:all .2s cubic-bezier(.4,0,.2,1);margin-top:1px;background:var(--background-surface)}
.check-item:hover .check-box{border-color:var(--cat-color)}
.check-item.ticked .check-box{background:var(--positive);border-color:var(--positive);box-shadow:0 0 0 4px color-mix(in srgb,var(--positive) 18%,transparent)}
.check-box svg{opacity:0;transform:scale(0.4);transition:all .25s cubic-bezier(.34,1.56,.64,1);width:11px;height:11px}
.check-item.ticked .check-box svg{opacity:1;transform:scale(1)}
.check-item .ci-content{flex:1;min-width:0}
.ci-head{display:flex;align-items:flex-start;justify-content:space-between;gap:.5rem}
.check-item .ci-text{font-size:.84rem;font-weight:600;color:var(--foreground);line-height:1.42}
.check-item.ticked .ci-text{color:var(--foreground-dim);text-decoration:line-through;text-decoration-color:color-mix(in srgb,var(--foreground-dim) 35%,transparent);text-decoration-thickness:1.5px}
.req-mark{flex-shrink:0;font-size:.62rem;font-weight:800;color:var(--negative);margin-left:.2rem}
.check-item .ci-hint{font-size:.72rem;color:var(--foreground-dim);line-height:1.45;margin-top:.5rem;display:flex;align-items:flex-start;gap:.4rem;background:var(--background-surface);border-radius:var(--radius-md);padding:.45rem .6rem}
.check-item .ci-hint .hint-icon{flex-shrink:0;line-height:1.4}
.check-item.ticked .ci-hint{opacity:.55}
.check-item .ci-meta{margin-top:.55rem;display:flex}
.item-cat-badge{display:inline-flex;align-items:center;gap:.3rem;font-size:.6rem;font-weight:700;text-transform:uppercase;letter-spacing:.05em;padding:.16rem .55rem;border-radius:var(--radius-full);background:color-mix(in srgb,var(--cat-color) 16%,transparent);color:var(--cat-color)}

/* Legacy badge classes — still used by the JS-generated warning-modal list
   (this page's proceed() builds `class="li-cat cat-<category>"` directly in
   JS for each unticked item), kept here for that; the grid's own item cards
   use .item-cat-badge (above) with the --cat-color custom property instead. */
.cat-badge{font-size:.55rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;padding:1px 6px;border-radius:var(--radius-full)}
.cat-setup{background:color-mix(in srgb,var(--primary) 14%,transparent);color:var(--primary)}
.cat-entry{background:color-mix(in srgb,var(--positive) 14%,transparent);color:var(--positive)}
.cat-risk{background:color-mix(in srgb,var(--warning) 14%,transparent);color:var(--warning)}
.cat-execution{background:color-mix(in srgb,#a78bfa 14%,transparent);color:#a78bfa}

/* Gate bar */
.gatebar{background:color-mix(in srgb,var(--background-elevated) 90%,transparent);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);border:1px solid var(--border);border-radius:var(--radius-xl);padding:1rem 1.35rem;display:flex;align-items:center;gap:1.1rem;position:sticky;bottom:1.1rem;flex-wrap:wrap;box-shadow:0 16px 36px rgba(0,0,0,.4)}
.gatebar .stat{font-size:.78rem;color:var(--foreground-dim);display:flex;align-items:center;gap:.45rem;font-weight:600}
.gatebar .stat .stat-icon{font-size:1rem;line-height:1}
.gatebar .stat b{color:var(--foreground);font-family:var(--font-mono);font-size:.95rem}
.gatebar .spacer{flex:1}
.gatebar .completed-msg{font-size:.8rem;color:var(--warning);font-weight:700;text-align:right;display:flex;align-items:center;gap:.4rem}

/* Unticked Items Warning Modal */
.modal-overlay-warn{display:none;position:fixed;inset:0;background:rgba(0,0,0,0.65);backdrop-filter:blur(3px);z-index:110;align-items:center;justify-content:center;padding:1rem}
.modal-overlay-warn.show{display:flex}
.modal-card-warn{background:var(--background-elevated);border:1px solid var(--border);border-top:3px solid var(--negative);border-radius:var(--radius-xl);padding:1.5rem 1.75rem;max-width:480px;width:100%;max-height:85vh;display:flex;flex-direction:column;position:relative;overflow:hidden;box-shadow:0 24px 60px rgba(0,0,0,.5)}
.modal-card-warn .modal-icon{width:2.35rem;height:2.35rem;border-radius:var(--radius-lg);background:color-mix(in srgb,var(--negative) 14%,transparent);border:1px solid color-mix(in srgb,var(--negative) 30%,transparent);display:flex;align-items:center;justify-content:center;font-size:1.05rem;margin-bottom:.6rem;flex-shrink:0}
.modal-card-warn .modal-title{font-size:1rem;font-weight:700;color:var(--foreground);margin-bottom:.15rem}
.modal-card-warn .modal-subtitle{font-size:.78rem;color:var(--foreground-dim);margin-bottom:1rem;line-height:1.45}
.modal-card-warn .modal-list{list-style:none;padding:0;margin:0 0 1.25rem;display:flex;flex-direction:column;gap:.4rem;overflow-y:auto;flex:1}
.modal-card-warn .modal-list li{font-size:.82rem;color:var(--foreground-muted);line-height:1.4;padding:.55rem .7rem;background:var(--background-surface);border-radius:var(--radius-md);border:1px solid var(--border);border-left:2px solid var(--negative);display:flex;align-items:center;gap:.55rem}
.modal-card-warn .modal-list li .li-num{font-family:var(--font-mono);font-size:.62rem;font-weight:600;color:var(--foreground-dim);background:var(--background-elevated);border-radius:var(--radius-sm);padding:.1rem .35rem;flex-shrink:0}
.modal-card-warn .modal-list li .li-text{flex:1;color:var(--foreground);font-weight:500}
.modal-card-warn .modal-list li .li-cat{flex-shrink:0;font-size:.55rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;padding:1px 6px;border-radius:var(--radius-full)}
.modal-card-warn .modal-actions{display:flex;gap:.5rem;flex-wrap:wrap;flex-shrink:0;padding-top:.25rem}
.modal-card-warn .btn-ghost{background:transparent;color:var(--foreground-muted);border:1px solid var(--border);padding:.5rem 1rem;border-radius:var(--radius-md);cursor:pointer;font-size:.8rem;font-weight:500;transition:all var(--t-fast)}
.modal-card-warn .btn-ghost:hover{background:var(--background-surface);color:var(--foreground)}
.modal-card-warn .btn-danger{background:var(--negative);color:#fff;border:none;padding:.5rem 1.25rem;border-radius:var(--radius-md);cursor:pointer;font-size:.8rem;font-weight:600;transition:all var(--t-fast)}
.modal-card-warn .btn-danger:hover{opacity:.9}

@media(max-width:768px){.main{padding:1.25rem 1.25rem 6rem}.checklist-grid{grid-template-columns:1fr}.selector-row{flex-direction:column;align-items:stretch}.selector-row-left{flex-direction:column;align-items:stretch}.gatebar{justify-content:center;text-align:center}.gatebar .completed-msg{text-align:center;justify-content:center;width:100%}}
</style>
</head>
<body class="dash-layout">

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

<main class="main">
    <?php if (!$account): ?>
        <a href="/traderalign/trading-center" class="back-link">← Back to Trading Center</a>
        <div class="page-head">
            <div class="page-icon">📐</div>
            <h1 class="page-title">Strategies</h1>
        </div>
        <p class="page-sub">Pick a strategy to switch what Dashboard, Reports, and Drafts are analyzing. Preparing an actual trade instead? Pick an account in Trading Center first.</p>

        <div class="selector-row">
            <div class="selector-row-left">
                <?php spRenderStrategyPicker($allStrategies, $selectedId, '/traderalign/dashboard', [], 'strategy_id'); ?>
            </div>
        </div>
    <?php else: ?>
        <a href="/traderalign/trading-center?hub=accounts&kind=<?= $isPropFirm ? 'prop' : 'live' ?>&view=center&account_id=<?= urlencode($account['id']) ?>" class="back-link">← <?= htmlspecialchars($account['label']) ?><?= $accountStatusLabel ? ' · ' . htmlspecialchars($accountStatusLabel) : '' ?></a>
        <div class="page-head">
            <div class="page-icon">🧭</div>
            <h1 class="page-title">Strategy</h1>
        </div>
        <p class="page-sub">Select a strategy, tick the items that are true for this setup, then proceed to the calculator.</p>

        <div class="selector-row">
            <div class="selector-row-left">
                <?php spRenderStrategyPicker($allStrategies, $selectedId, '/traderalign/strategies', ['account_id' => $account['id']]); ?>
                <?php if ($version): ?>
                <div class="strategy-stats">
                    <?php if ($version['max_risk_per_trade_pct'] !== null): ?>
                    <div class="stat-chip"><span class="sc-val"><?= rtrim(rtrim(number_format((float)$version['max_risk_per_trade_pct'], 2), '0'), '.') ?>%</span><span class="sc-lbl">Risk</span></div>
                    <?php endif; ?>
                    <?php if ($version['backtested_avg_rr'] !== null): ?>
                    <div class="stat-chip"><span class="sc-val">1:<?= rtrim(rtrim(number_format((float)$version['backtested_avg_rr'], 2), '0'), '.') ?></span><span class="sc-lbl">Avg R:R</span></div>
                    <?php endif; ?>
                    <?php if ($version['backtested_win_rate'] !== null): ?>
                    <div class="stat-chip"><span class="sc-val"><?= rtrim(rtrim(number_format((float)$version['backtested_win_rate'], 1), '0'), '.') ?>%</span><span class="sc-lbl">Win Rate</span></div>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </div>
            <?php
            // 2026-08-20: workflow-aware — previously always pointed at
            // /traderalign/strategy (main-workflow-only, gated by
            // ValidationService::gateMainWorkflowOnly()), so a validating
            // user landed here and got silently redirected to Validation
            // Tracker instead, unrelated to "I forgot my strategy." Same
            // ?mode=readonly&strategy_id=X&back_account_id=Y shape either
            // way, just a different target page — strategy-validation.php's
            // own real readonly viewer for validation, strategy.php's for
            // main, exact parity between the two workflows.
            $forgotStrategyUrl = ($isValidatingWorkflow ? '/traderalign/strategy-validation' : '/traderalign/strategy')
                . '?strategy_id=' . urlencode($selectedId) . '&mode=readonly&back_account_id=' . urlencode($account['id']);
            ?>
            <a class="forgot-link" href="<?= htmlspecialchars($forgotStrategyUrl) ?>">Forgot strategy?</a>
        </div>

        <?php if (empty($items)): ?>
        <div class="empty-state">
            <div class="es-icon">📋</div>
            <h3 style="color:var(--foreground);margin-bottom:.5rem">No checklist items for this strategy</h3>
            <p>This strategy doesn't have checklist items yet. Build them in the Strategy Panel first.</p>
            <a class="btn btn-primary btn-md" style="margin-top:1.5rem" href="/traderalign/strategy">Open Strategy Panel</a>
        </div>
        <?php else: ?>

        <div class="progress-card">
            <span class="prog-label"><span class="prog-icon">✅</span>Progress</span>
            <div class="prog-bar"><div class="prog-fill" id="prog" style="width:0%"></div></div>
            <span class="prog-pct" id="pct">0%</span>
        </div>

        <div class="checklist-grid" id="items">
            <?php $currentCategory = ''; foreach ($items as $item): if ($item['category'] !== $currentCategory): $currentCategory = $item['category']; $cm = spCatMeta($catMeta, $currentCategory); ?>
            <div class="cat-header" style="--cat-color:<?= $cm['color'] ?>"><span class="cat-header-icon"><?= $cm['icon'] ?></span><?= htmlspecialchars($cm['label']) ?></div>
            <?php endif; $im = spCatMeta($catMeta, $item['category']); ?>
            <div class="check-item" style="--cat-color:<?= $im['color'] ?>" data-id="<?= htmlspecialchars($item['id']) ?>" data-required="<?= $item['is_required'] ? '1' : '0' ?>" onclick="toggleItem(this)">
                <div class="ci-top">
                    <div class="check-box"><svg viewBox="0 0 12 12"><path d="M2 6.5L5 9.5L10 3" stroke="#FFFFFF" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg></div>
                    <div class="ci-content">
                        <div class="ci-head">
                            <div class="ci-text"><?= htmlspecialchars($item['polished_text'] ?: $item['raw_text']) ?><?php if ($item['is_required']): ?><span class="req-mark" title="Required item">●</span><?php endif; ?></div>
                        </div>
                        <?php if (!empty($item['verification_hint'])): ?>
                        <div class="ci-hint"><span class="hint-icon">💡</span><span><?= htmlspecialchars($item['verification_hint']) ?></span></div>
                        <?php endif; ?>
                        <div class="ci-meta"><span class="item-cat-badge"><?= $im['icon'] ?> <?= htmlspecialchars($im['label']) ?></span></div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

        <div class="gatebar">
            <div class="stat"><span class="stat-icon">📌</span>Required: <b id="reqCount">0/0</b></div>
            <?php if ($isCompletedPhase): ?>
            <div class="spacer"></div>
            <div class="completed-msg">⚠️ This phase is complete. Promote to the next phase in Trading Center first.</div>
            <?php else: ?>
            <div class="spacer"></div>
            <button class="btn btn-primary btn-lg" id="proceedBtn" onclick="proceed()">Proceed to Calculator →</button>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    <?php endif; ?>
</main>

<div class="modal-overlay-warn" id="warningModal">
    <div class="modal-card-warn">
        <div class="modal-icon">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--negative)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 9v4m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/></svg>
        </div>
        <div class="modal-title" id="modalTitle">Some items not ticked</div>
        <div class="modal-subtitle">Review what's missing, then go back or proceed at your own discretion.</div>
        <ul class="modal-list" id="modalList"></ul>
        <div class="modal-actions">
            <button class="btn-ghost" onclick="closeWarningModal()">Go Back</button>
            <button class="btn-danger" onclick="proceedAnyway()">Proceed Anyway →</button>
        </div>
    </div>
</div>

<script src="/traderalign/assets/js/account-picker.js"></script>
<script>
const itemsData = <?= json_encode($itemsData) ?>;
const versionId = <?= json_encode($version ? $version['id'] : null) ?>;
const isPropFirm = <?= json_encode($isPropFirm) ?>;
const isPersonal = <?= json_encode($isPersonal) ?>;
const isCompletedPhase = <?= json_encode($isCompletedPhase) ?>;
const accountId = <?= json_encode($account ? $account['id'] : null) ?>;
const accountLabel = <?= json_encode($account ? $account['label'] : null) ?>;

const accountStageData = <?= json_encode($isPropFirm && $account && $account['challenge_account_id'] ? [
    'challenge_account_id' => $account['challenge_account_id'],
    'challenge_type'       => $account['challenge_type'],
    'current_stage'        => $account['current_stage'] ?? 'phase_1',
    'lifecycle_state'      => $account['lifecycle_state'],
    'rules'                => json_decode($account['rules'] ?? '{}', true) ?: [],
    'custom_rules'         => json_decode($account['custom_rules'] ?? '[]', true) ?: [],
] : null) ?>;

let ticked = new Set();

function toggleItem(el) {
    if (isCompletedPhase) {
        alert('This phase is complete. Promote to the next phase in Trading Center first.');
        return;
    }
    const id = el.dataset.id;
    ticked.has(id) ? ticked.delete(id) : ticked.add(id);
    el.classList.toggle('ticked', ticked.has(id));
    updateStats();
}

function updateStats() {
    const total = itemsData.length;
    const c = [...ticked].filter(id => itemsData.find(i => i.id === id)).length;
    const req = itemsData.filter(i => i.is_required);
    const rt = req.filter(i => ticked.has(i.id)).length;
    const pct = total > 0 ? Math.round(c / total * 100) : 0;
    document.getElementById('pct').textContent = pct + '%';
    document.getElementById('reqCount').textContent = rt + '/' + req.length;
    document.getElementById('prog').style.width = pct + '%';
}

function uuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
        const r = Math.random() * 16 | 0;
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
}

function proceed() {
    if (isCompletedPhase) {
        alert('This phase is complete. Promote to the next phase in Trading Center first.');
        return;
    }
    const unticked = itemsData.filter(i => !ticked.has(i.id));
    if (unticked.length === 0) {
        submitChecklist();
        return;
    }
    const modalList = document.getElementById('modalList');
    document.getElementById('modalTitle').textContent = unticked.length + ' item' + (unticked.length > 1 ? 's' : '') + ' not ticked';
    modalList.innerHTML = unticked.map((item, i) =>
        '<li><span class="li-num">' + String(i + 1).padStart(2, '0') + '</span>' +
        '<span class="li-text">' + escapeHTML(item.text) + '</span>' +
        '<span class="li-cat cat-' + item.category + '">' + escapeHTML(item.category) + '</span></li>'
    ).join('');
    document.getElementById('warningModal').classList.add('show');
}

function closeWarningModal() { document.getElementById('warningModal').classList.remove('show'); }
function proceedAnyway() { closeWarningModal(); submitChecklist(); }
function escapeHTML(str) { const div = document.createElement('div'); div.textContent = str; return div.innerHTML; }

document.getElementById('warningModal').addEventListener('click', function(e) {
    if (e.target === this) closeWarningModal();
});
document.addEventListener('keydown', function(e) {
    if (!document.getElementById('warningModal').classList.contains('show')) return;
    if (e.key === 'Escape') closeWarningModal();
});

function submitChecklist() {
    const id = uuid();
    const ta = [...ticked];
    const ra = itemsData.filter(i => i.is_required).map(i => i.id);
    const pct = itemsData.length > 0 ? +(ta.filter(i => itemsData.find(x => x.id === i)).length / itemsData.length * 100).toFixed(2) : 0;

    const challengeAccountId = accountStageData ? accountStageData.challenge_account_id : null;
    const lifecycleState = accountStageData ? accountStageData.lifecycle_state : null;
    const challengeType = accountStageData ? accountStageData.challenge_type : null;
    const currentStage = accountStageData ? accountStageData.current_stage : null;
    const rules = accountStageData ? accountStageData.rules : null;

    try {
        sessionStorage.setItem('trade_lifecycle_id', id);
        sessionStorage.setItem('strategy_version_id', versionId);
        if (accountId) sessionStorage.setItem('account_id', accountId);
        if (challengeAccountId) sessionStorage.setItem('challenge_account_id', challengeAccountId);
        if (lifecycleState) sessionStorage.setItem('lifecycle_state', lifecycleState);
        if (challengeType) sessionStorage.setItem('challenge_type', challengeType);
        if (currentStage) sessionStorage.setItem('current_stage', currentStage);
        if (rules) sessionStorage.setItem('account_rules', JSON.stringify(rules));
        sessionStorage.setItem('prop_firm_mode', isPropFirm ? 'true' : 'false');
    } catch (e) {
        console.error('Failed to save to sessionStorage:', e);
    }

    let calcUrl = '/traderalign/calculator';
    const params = new URLSearchParams();
    if (accountId) params.append('account_id', accountId);
    if (challengeAccountId) params.append('challenge_account_id', challengeAccountId);
    if (lifecycleState) params.append('lifecycle_state', lifecycleState);
    if (challengeType) params.append('challenge_type', challengeType);
    if (currentStage) params.append('current_stage', currentStage);
    if (accountLabel) params.append('account_label', accountLabel);
    if (isPropFirm) {
        params.append('prop_firm_mode', 'true');
        if (rules) {
            Object.entries(rules).forEach(([key, val]) => {
                if (val !== null && val !== undefined) params.append(key, val);
            });
        }
    }
    const queryString = params.toString();
    if (queryString) calcUrl += '?' + queryString;

    fetch('/traderalign/api/checklist/save', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            trade_lifecycle_id: id,
            strategy_version_id: versionId,
            account_id: accountId,
            challenge_account_id: challengeAccountId,
            lifecycle_state: lifecycleState,
            items_ticked: ta,
            items_required: ra,
            ticked_pct: pct,
            status: 'pending_calculator',
            ticked_at: new Date().toISOString(),
            expires_at: new Date(Date.now() + 24 * 3600 * 1000).toISOString()
        })
    })
    .then(r => r.json())
    .then(d => {
        if (d.error) { alert(d.error); return; }
        window.location.href = calcUrl;
    })
    .catch(e => {
        console.error('Checklist save failed:', e);
        window.location.href = calcUrl;
    });
}

if (isCompletedPhase) {
    document.querySelectorAll('.check-item').forEach(item => {
        item.style.pointerEvents = 'none';
        item.style.opacity = '0.5';
        item.title = 'Checklist items cannot be modified for completed phases';
    });
}

updateStats();
</script>
</body>
</html>
