<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New Optimization — MT5 Smart Optimizer</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<style>
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
  :root {
    --bg:     #07090f;
    --bg2:    #0d1117;
    --bg3:    #141b27;
    --bg4:    #1a2335;
    --border: rgba(255,255,255,0.08);
    --accent: #00d4aa;
    --accent2:#7c6dfa;
    --warn:   #f59e0b;
    --danger: #ef4444;
    --text:   #e2e8f0;
    --muted:  #64748b;
    --glow:   0 0 30px rgba(0,212,170,0.12);
  }
  html { scroll-behavior: smooth; }
  body {
    font-family: 'Inter', sans-serif;
    background: var(--bg);
    color: var(--text);
    min-height: 100vh;
    padding: 2rem 1rem 4rem;
  }
  body::before {
    content:''; position:fixed; inset:0;
    background-image: linear-gradient(rgba(0,212,170,0.025) 1px,transparent 1px),
                      linear-gradient(90deg,rgba(0,212,170,0.025) 1px,transparent 1px);
    background-size: 60px 60px;
    pointer-events:none; z-index:0;
  }

  .page { position:relative; z-index:1; max-width: 780px; margin: 0 auto; }

  /* Header */
  .header {
    display: flex; align-items: center; gap: 1rem;
    margin-bottom: 2.5rem;
    padding-bottom: 1.5rem;
    border-bottom: 1px solid var(--border);
  }
  .back-btn {
    display: inline-flex; align-items: center; gap: 0.4rem;
    color: var(--muted); text-decoration: none;
    font-size: 0.875rem; transition: color 0.2s;
  }
  .back-btn:hover { color: var(--text); }
  .header-title { font-size: 1.5rem; font-weight: 800; letter-spacing:-0.03em; }
  .header-sub { font-size: 0.85rem; color: var(--muted); margin-top: 0.1rem; }

  /* Section cards */
  .section {
    background: var(--bg2);
    border: 1px solid var(--border);
    border-radius: 16px;
    padding: 1.5rem;
    margin-bottom: 1.25rem;
    transition: border-color 0.2s;
  }
  .section:hover { border-color: rgba(255,255,255,0.13); }
  .section-title {
    font-size: 0.8rem; font-weight: 600;
    text-transform: uppercase; letter-spacing: 0.1em;
    color: var(--accent); margin-bottom: 1.25rem;
    display: flex; align-items: center; gap: 0.5rem;
  }

  /* Form grid */
  .grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
  .grid-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 1rem; }

  .field { display: flex; flex-direction: column; gap: 0.45rem; }
  .field label { font-size: 0.8rem; color: var(--muted); font-weight: 500; }

  input, select {
    background: var(--bg3);
    border: 1px solid var(--border);
    border-radius: 10px;
    color: var(--text);
    font-family: inherit;
    font-size: 0.95rem;
    padding: 0.65rem 0.9rem;
    transition: border-color 0.2s, box-shadow 0.2s;
    width: 100%;
    -webkit-appearance: none;
  }
  input:focus, select:focus {
    outline: none;
    border-color: var(--accent);
    box-shadow: 0 0 0 3px rgba(0,212,170,0.12);
  }
  select { background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%2364748b' d='M6 8L1 3h10z'/%3E%3C/svg%3E"); background-repeat:no-repeat; background-position: right 0.9rem center; padding-right: 2.2rem; cursor:pointer; }

  /* Budget pills */
  .pill-group { display: flex; gap: 0.5rem; flex-wrap: wrap; }
  .pill {
    padding: 0.55rem 1.2rem;
    border-radius: 999px;
    border: 1px solid var(--border);
    background: var(--bg3);
    font-size: 0.875rem;
    cursor: pointer;
    font-family: inherit;
    color: var(--muted);
    transition: all 0.2s;
    font-weight: 500;
    position: relative;
  }
  .pill:hover { border-color: var(--accent); color: var(--text); }
  .pill.active {
    background: rgba(0,212,170,0.15);
    border-color: var(--accent);
    color: var(--accent);
  }
  .pill .badge {
    position: absolute; top: -7px; right: -4px;
    background: var(--accent2); color: white;
    font-size: 0.6rem; padding: 0 5px; border-radius: 999px; font-weight:600;
  }

  /* Objective cards */
  .obj-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 0.75rem; }
  .obj-card {
    background: var(--bg3);
    border: 2px solid var(--border);
    border-radius: 12px;
    padding: 1rem;
    cursor: pointer;
    transition: all 0.2s;
    text-align: center;
  }
  .obj-card:hover { border-color: rgba(255,255,255,0.2); }
  .obj-card.active { border-color: var(--accent); background: rgba(0,212,170,0.08); }
  .obj-icon { font-size: 1.6rem; margin-bottom: 0.4rem; }
  .obj-name { font-size: 0.85rem; font-weight: 600; }
  .obj-desc { font-size: 0.72rem; color: var(--muted); margin-top: 0.2rem; }

  /* Advanced toggle */
  .adv-toggle {
    display: flex; align-items: center; gap: 0.6rem;
    cursor: pointer;
    color: var(--muted); font-size: 0.85rem;
    padding: 0.6rem 0;
    user-select: none;
    width: fit-content;
  }
  .adv-toggle:hover { color: var(--text); }
  .adv-toggle svg { transition: transform 0.2s; }
  .adv-toggle.open svg { transform: rotate(90deg); }
  .adv-body { display: none; margin-top: 1rem; }
  .adv-body.open { display: block; }

  /* Param checkboxes */
  .param-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 0.5rem; }
  .param-check { display: flex; align-items: center; gap: 0.6rem; cursor: pointer; padding: 0.4rem 0.6rem; border-radius: 8px; transition: background 0.15s; }
  .param-check:hover { background: var(--bg4); }
  .param-check input { width: 16px; height: 16px; accent-color: var(--accent); cursor: pointer; }
  .param-check span { font-size: 0.82rem; }

  /* Submit */
  .submit-row {
    display: flex; gap: 1rem; align-items: center;
    margin-top: 2rem; padding-top: 1.5rem;
    border-top: 1px solid var(--border);
  }
  .btn-start {
    padding: 0.95rem 2.5rem;
    background: linear-gradient(135deg, var(--accent), #00b890);
    color: #051a14;
    border: none; border-radius: 12px;
    font-size: 1rem; font-weight: 700;
    cursor: pointer; font-family: inherit;
    transition: all 0.2s;
    box-shadow: 0 4px 24px rgba(0,212,170,0.3);
    display: flex; align-items: center; gap: 0.6rem;
  }
  .btn-start:hover { transform: translateY(-2px); box-shadow: 0 8px 36px rgba(0,212,170,0.45); }
  .btn-start:active { transform: translateY(0); }
  .btn-start:disabled { opacity: 0.5; pointer-events: none; }

  .estimate { color: var(--muted); font-size: 0.85rem; }
  .estimate strong { color: var(--accent); }

  /* Hint row */
  .hint {
    background: rgba(0,212,170,0.06);
    border: 1px solid rgba(0,212,170,0.15);
    border-radius: 10px;
    padding: 0.75rem 1rem;
    font-size: 0.82rem;
    color: var(--muted);
    line-height: 1.6;
  }

  @media (max-width: 600px) {
    .grid-2, .grid-3, .obj-grid { grid-template-columns: 1fr; }
  }
</style>
</head>
<body>
<div class="page">

  <!-- Header -->
  <div class="header">
    <a href="/" class="back-btn">
      <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M3.83 7H14a.5.5 0 010 1H3.83l3.58 3.59a.5.5 0 01-.7.71l-4.5-4.5a.5.5 0 010-.71l4.5-4.5a.5.5 0 11.7.71L3.83 7z"/></svg>
      Back
    </a>
    <div>
      <div class="header-title">⚡ New Optimization</div>
      <div class="header-sub">Configure and launch a smart EA optimization session</div>
    </div>
  </div>

  <form id="setup-form" novalidate>

    <!-- EA Identity -->
    <!-- ── Pre-flight check ─────────────────────────────────────── -->
    <div class="section" id="preflight-section" style="margin-bottom:14px;">
      <div class="section-title">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M9 12l2 2 4-4"/></svg>
        Pre-flight check
        <span id="preflight-status" style="margin-left:auto;font-size:0.78rem;color:#64748b;font-weight:500;">running…</span>
      </div>
      <div id="preflight-list" style="display:flex;flex-direction:column;gap:6px;font-size:0.82rem;"></div>
    </div>
    <style>
      .pf-row { display:flex; align-items:flex-start; gap:8px; padding:6px 10px; border-radius:6px; background:rgba(255,255,255,0.03); border:1px solid rgba(255,255,255,0.05); }
      .pf-row.ok   { border-color: rgba(16,185,129,0.3); }
      .pf-row.warn { border-color: rgba(245,158,11,0.3); background: rgba(245,158,11,0.05); }
      .pf-row.err  { border-color: rgba(239,68,68,0.3); background: rgba(239,68,68,0.05); }
      .pf-mark { width:14px; flex-shrink:0; font-weight:700; }
      .pf-row.ok   .pf-mark { color:#10b981; }
      .pf-row.warn .pf-mark { color:#f59e0b; }
      .pf-row.err  .pf-mark { color:#ef4444; }
      .pf-name { font-weight:600; color:#e2e8f0; }
      .pf-hint { display:block; font-size:0.72rem; color:#94a3b8; margin-top:2px; line-height:1.4; }
    </style>

    <div class="section">
      <div class="section-title">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="3"/><path d="M9 12l2 2 4-4"/></svg>
        EA Configuration
      </div>
      <div class="grid-3">
        <div class="field">
          <label for="ea_name">Expert Advisor</label>
          <select id="ea_name" name="ea_name">
            {% for ea in registered_eas %}
            <option value="{{ ea.name }}" {% if ea.name == default_ea %}selected{% endif %}>{{ ea.name }}</option>
            {% endfor %}
          </select>
        </div>
        <div class="field">
          <label for="symbol">Symbol</label>
          <select id="symbol" name="symbol">
            <option value="XAUUSD" selected>XAUUSD (Gold)</option>
            <option value="EURUSD">EURUSD</option>
            <option value="GBPUSD">GBPUSD</option>
            <option value="USDJPY">USDJPY</option>
            <option value="USDCHF">USDCHF</option>
            <option value="USDCAD">USDCAD</option>
            <option value="AUDUSD">AUDUSD</option>
            <option value="BTCUSD">BTCUSD</option>
            <option value="NASDAQ">NASDAQ</option>
          </select>
        </div>
        <div class="field">
          <label for="timeframe">Timeframe</label>
          <select id="timeframe" name="timeframe">
            <option value="M15">M15</option>
            <option value="M30">M30</option>
            <option value="H1" selected>H1</option>
            <option value="H4">H4</option>
            <option value="D1">D1</option>
          </select>
        </div>
      </div>
    </div>

    <!-- Periods -->
    <div class="section">
      <div class="section-title">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg>
        Date Ranges
      </div>
      <div class="grid-2" style="margin-bottom:1rem">
        <div class="field">
          <label for="train_start">Training From</label>
          <input type="date" id="train_start" name="train_start" value="2022-01-01">
        </div>
        <div class="field">
          <label for="train_end">Training To</label>
          <input type="date" id="train_end" name="train_end" value="2023-12-31">
        </div>
      </div>
      <div class="grid-2">
        <div class="field">
          <label for="val_start">Validation From (Out-of-Sample)</label>
          <input type="date" id="val_start" name="val_start" value="2024-01-01">
        </div>
        <div class="field">
          <label for="val_end">Validation To</label>
          <input type="date" id="val_end" name="val_end" value="2024-06-30">
        </div>
      </div>
      <div class="hint" style="margin-top:1rem">
        <strong>Tip:</strong> Training period is where the optimizer searches for settings.
        Validation is unseen data — the optimizer never touches it until Phase 3.
        Keep validation at least 6 months.
      </div>
    </div>

    <!-- Budget -->
    <div class="section">
      <div class="section-title">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>
        Time Budget
      </div>
      <div class="pill-group">
        <button type="button" class="pill" data-budget="30" onclick="setBudget(30)">
          ⚡ 30 min
          <span class="badge">~15 tests</span>
        </button>
        <button type="button" class="pill active" data-budget="60" onclick="setBudget(60)">
          ⏱ 1 hour
          <span class="badge">~35 tests</span>
        </button>
        <button type="button" class="pill" data-budget="120" onclick="setBudget(120)">
          🌙 2 hours
          <span class="badge">~70 tests</span>
        </button>
      </div>
      <input type="hidden" id="budget_minutes" name="budget_minutes" value="60">
    </div>

    <!-- Objective -->
    <div class="section">
      <div class="section-title">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>
        Optimize For
      </div>
      <div class="obj-grid">
        <div class="obj-card active" data-obj="balanced" onclick="setObj('balanced')">
          <div class="obj-icon">⚖️</div>
          <div class="obj-name">Balanced</div>
          <div class="obj-desc">Good profit + Low drawdown</div>
        </div>
        <div class="obj-card" data-obj="max_profit" onclick="setObj('max_profit')">
          <div class="obj-icon">📈</div>
          <div class="obj-name">Max Profit</div>
          <div class="obj-desc">Highest return, any risk</div>
        </div>
        <div class="obj-card" data-obj="min_drawdown" onclick="setObj('min_drawdown')">
          <div class="obj-icon">🛡️</div>
          <div class="obj-name">Low Risk</div>
          <div class="obj-desc">Minimum drawdown first</div>
        </div>
      </div>
      <input type="hidden" id="objective" name="objective" value="balanced">
    </div>

    <!-- Advanced: Param Selection -->
    <div class="section">
      <div class="adv-toggle" id="adv-toggle" onclick="toggleAdv()">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M9 18l6-6-6-6"/></svg>
        Advanced: Select Parameters to Optimize
        <span style="color:var(--muted);font-size:0.78rem;margin-left:0.25rem">(optional)</span>
      </div>
      <div class="adv-body" id="adv-body">
        <p style="font-size:0.82rem;color:var(--muted);margin-bottom:1rem">
          Leave all checked to let the optimizer decide. Uncheck parameters you want to keep fixed.
        </p>
        <div class="param-grid" id="param-grid">
          {% for p in params %}
          <label class="param-check">
            <input type="checkbox" name="selected_params" value="{{ p.name }}"
              {% if p.optimize %}checked{% endif %}
              {% if p.type == 'fixed' %}disabled{% endif %}>
            <span title="{{ p.range_label }}">{{ p.name.replace('Inp','') }}</span>
          </label>
          {% endfor %}
        </div>
      </div>
    </div>

    <!-- Add New EA -->
    <div style="margin-top:0.5rem;display:flex;gap:0.75rem;align-items:center;flex-wrap:wrap">
      <button type="button" onclick="showAddEAModal()"
        style="background:none;border:1px dashed rgba(79,70,229,0.4);color:#7c6dfa;padding:0.4rem 1rem;border-radius:8px;font-size:0.8rem;cursor:pointer;font-family:inherit;transition:all 0.2s"
        onmouseover="this.style.borderColor='#7c6dfa'" onmouseout="this.style.borderColor='rgba(79,70,229,0.4)'">
        + Register New EA
      </button>
      <button type="button" id="scan-btn" onclick="scanForEAs()"
        style="background:none;border:1px dashed rgba(0,212,170,0.35);color:#00d4aa;padding:0.4rem 1rem;border-radius:8px;font-size:0.8rem;cursor:pointer;font-family:inherit;transition:all 0.2s;display:flex;align-items:center;gap:0.4rem"
        onmouseover="this.style.borderColor='#00d4aa'" onmouseout="this.style.borderColor='rgba(0,212,170,0.35)'">
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>
        Scan for EAs
      </button>
      <span id="scan-status" style="font-size:0.78rem;color:#64748b"></span>
    </div>

    <!-- Add EA Modal -->
    <div id="add-ea-modal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.75);z-index:50;align-items:center;justify-content:center;backdrop-filter:blur(6px)">
      <div style="background:#0d1117;border:1px solid rgba(255,255,255,0.1);border-radius:16px;padding:2rem;width:540px;max-width:95vw;max-height:90vh;overflow-y:auto">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1.5rem">
          <div>
            <h3 style="font-size:1.05rem;font-weight:700;color:#e2e8f0">Register New EA</h3>
            <p style="font-size:0.78rem;color:#64748b;margin-top:0.2rem">Pick a detected EA or enter paths manually</p>
          </div>
          <button onclick="hideAddEAModal()" style="background:none;border:none;color:#64748b;cursor:pointer;font-size:1.4rem;line-height:1">&#10005;</button>
        </div>

        <!-- Detected EAs picker (shown after scan) -->
        <div id="detected-section" style="display:none;margin-bottom:1.25rem">
          <div style="font-size:0.78rem;font-weight:600;text-transform:uppercase;letter-spacing:0.08em;color:#00d4aa;margin-bottom:0.6rem">
            Detected EAs — click to auto-fill
          </div>
          <div id="detected-list" style="display:flex;flex-direction:column;gap:0.4rem;max-height:180px;overflow-y:auto;padding-right:4px"></div>
          <div style="margin:1rem 0;border-top:1px solid rgba(255,255,255,0.06)"></div>
        </div>

        <div style="display:flex;flex-direction:column;gap:1rem">
          <div class="field">
            <label>EA Display Name</label>
            <input type="text" id="new-ea-name" placeholder="e.g. MyEA_v2">
          </div>
          <div class="field">
            <label>EA File Name (without .ex5)</label>
            <input type="text" id="new-ea-file" placeholder="e.g. MyEA_v2">
          </div>
          <div class="field">
            <label style="display:flex;align-items:center;justify-content:space-between">
              <span>.set Template Path</span>
              <span id="set-match-badge" style="display:none;font-size:0.7rem;background:rgba(0,212,170,0.15);color:#00d4aa;padding:2px 8px;border-radius:999px;font-weight:600">✓ auto-matched</span>
            </label>
            <input type="text" id="new-ea-set" placeholder="C:\MT5 Set files\MyEA.set">
            <!-- Set file picker (shown after scan) -->
            <select id="set-picker" style="display:none;margin-top:0.4rem;font-size:0.82rem" onchange="onSetPick()">
              <option value="">— pick from detected .set files —</option>
            </select>
          </div>
          <div class="grid-2">
            <div class="field">
              <label>Symbol</label>
              <select id="new-ea-symbol">
                <option value="XAUUSD">XAUUSD (Gold)</option>
                <option value="EURUSD">EURUSD</option>
                <option value="GBPUSD">GBPUSD</option>
                <option value="USDJPY">USDJPY</option>
                <option value="USDCAD">USDCAD</option>
                <option value="AUDUSD">AUDUSD</option>
                <option value="BTCUSD">BTCUSD</option>
                <option value="NASDAQ">NASDAQ</option>
                <option value="US30">US30</option>
                <option value="DE40">DE40</option>
              </select>
            </div>
            <div class="field">
              <label>Timeframe</label>
              <select id="new-ea-tf">
                <option value="M5">M5</option>
                <option value="M15">M15</option>
                <option value="M30">M30</option>
                <option value="H1" selected>H1</option>
                <option value="H4">H4</option>
                <option value="D1">D1</option>
              </select>
            </div>
          </div>
        </div>

        <div style="display:flex;gap:0.75rem;margin-top:1.5rem;justify-content:flex-end">
          <button type="button" onclick="hideAddEAModal()"
            style="padding:0.6rem 1.25rem;background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.1);color:#e2e8f0;border-radius:8px;cursor:pointer;font-family:inherit">
            Cancel
          </button>
          <button type="button" onclick="registerNewEA()"
            style="padding:0.6rem 1.5rem;background:linear-gradient(135deg,#4f46e5,#7c6dfa);color:white;border:none;border-radius:8px;font-weight:700;cursor:pointer;font-family:inherit">
            Register EA
          </button>
        </div>
      </div>
    </div>

    <!-- Autonomous AI Loop -->
    <div style="border:1px solid rgba(0,212,170,0.25);border-radius:12px;padding:1.25rem 1.5rem;background:rgba(0,212,170,0.04);margin-top:0.5rem">
      <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:0.75rem">
        <div>
          <div style="display:flex;align-items:center;gap:0.6rem">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#00d4aa" stroke-width="2"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
            <span style="font-size:0.88rem;font-weight:700;color:#e2e8f0">Autonomous AI Loop</span>
            <span style="font-size:0.62rem;background:rgba(0,212,170,0.18);color:#00d4aa;padding:2px 7px;border-radius:999px;font-weight:700;letter-spacing:0.05em">NEW</span>
          </div>
          <div style="font-size:0.72rem;color:#64748b;margin-top:0.25rem">
            AI analyzes results and evolves parameters each iteration until targets are met
          </div>
        </div>
        <!-- Toggle -->
        <button type="button" class="settings-toggle" id="autonomous-toggle"
          onclick="toggleAutonomous(this)"
          style="width:44px;height:24px;background:rgba(255,255,255,0.12);border-radius:999px;border:none;cursor:pointer;position:relative;transition:background 0.2s;flex-shrink:0">
        </button>
      </div>

      <!-- Expanded controls (hidden when off) -->
      <div id="autonomous-controls" style="display:none">
        <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:0.75rem;margin-bottom:0.75rem">
          <div class="field" style="margin:0">
            <label>Max Iterations</label>
            <input type="number" name="autonomous_max_iterations" id="ai-max-iter"
              value="10" min="3" max="50" step="1" class="input" style="margin-top:0.3rem">
          </div>
          <div class="field" style="margin:0">
            <label>Target Profit Factor</label>
            <input type="number" name="target_profit_factor" id="ai-target-pf"
              value="1.5" min="1.0" max="5.0" step="0.1" class="input" style="margin-top:0.3rem">
          </div>
          <div class="field" style="margin:0">
            <label>Target Max Drawdown %</label>
            <input type="number" name="target_max_drawdown_pct" id="ai-target-dd"
              value="20" min="5" max="50" step="1" class="input" style="margin-top:0.3rem">
          </div>
        </div>
        <div style="display:grid;grid-template-columns:1fr 2fr;gap:0.75rem">
          <div class="field" style="margin:0">
            <label>Target Min Calmar</label>
            <input type="number" name="target_min_calmar" id="ai-target-calmar"
              value="0.5" min="0.1" max="5.0" step="0.05" class="input" style="margin-top:0.3rem">
          </div>
          <div style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.07);border-radius:8px;padding:0.6rem 0.9rem;font-size:0.72rem;color:#64748b;line-height:1.55">
            Loop stops early when <strong style="color:#e2e8f0">ALL</strong> targets are met simultaneously.
            Requires an Anthropic API key configured in Settings.
          </div>
        </div>
      </div>

      <!-- Hidden inputs for form submission -->
      <input type="hidden" name="autonomous_mode" id="autonomous-mode-val" value="false">
    </div>

    <!-- Submit -->
    <div class="submit-row">
      <button type="submit" class="btn-start" id="start-btn">
        <span>⚡</span> Start Optimization
      </button>
      <div class="estimate" id="estimate">
        Estimated: <strong id="est-runs">~35 tests</strong> in <strong id="est-time">~1 hour</strong>
      </div>
    </div>

  </form>
</div>

<script>
  let budget = 60;
  let objective = 'balanced';

  const estimates = {
    30:  {runs: '~15 tests', time: '~30 min'},
    60:  {runs: '~35 tests', time: '~1 hour'},
    120: {runs: '~70 tests', time: '~2 hours'},
  };

  function setBudget(val) {
    budget = val;
    document.getElementById('budget_minutes').value = val;
    document.querySelectorAll('.pill').forEach(p => {
      p.classList.toggle('active', parseInt(p.dataset.budget) === val);
    });
    const e = estimates[val] || estimates[60];
    document.getElementById('est-runs').textContent = e.runs;
    document.getElementById('est-time').textContent = e.time;
  }

  function setObj(val) {
    objective = val;
    document.getElementById('objective').value = val;
    document.querySelectorAll('.obj-card').forEach(c => {
      c.classList.toggle('active', c.dataset.obj === val);
    });
  }

  function toggleAdv() {
    const toggle = document.getElementById('adv-toggle');
    const body   = document.getElementById('adv-body');
    toggle.classList.toggle('open');
    body.classList.toggle('open');
  }

  let scannedData = null;  // cache from /api/ea/scan

  function showAddEAModal() {
    document.getElementById('add-ea-modal').style.display = 'flex';
    // If we already scanned, populate the detected section
    if (scannedData) populateDetected(scannedData);
  }

  function hideAddEAModal() {
    document.getElementById('add-ea-modal').style.display = 'none';
  }

  async function scanForEAs() {
    const btn = document.getElementById('scan-btn');
    const status = document.getElementById('scan-status');
    btn.style.opacity = '0.5';
    btn.style.pointerEvents = 'none';
    status.textContent = 'Scanning...';
    try {
      const resp = await fetch('/api/ea/scan');
      const data = await resp.json();
      scannedData = data;
      const count = data.ex5.length;
      const setCount = data.set.length;
      status.style.color = '#00d4aa';
      status.textContent = `Found ${count} EA${count !== 1 ? 's' : ''} · ${setCount} .set file${setCount !== 1 ? 's' : ''}`;
      showAddEAModal();
    } catch(e) {
      status.style.color = '#ef4444';
      status.textContent = 'Scan failed: ' + e.message;
    } finally {
      btn.style.opacity = '';
      btn.style.pointerEvents = '';
    }
  }

  function populateDetected(data) {
    const section = document.getElementById('detected-section');
    const list    = document.getElementById('detected-list');
    const picker  = document.getElementById('set-picker');

    if (!data.ex5.length && !data.set.length) return;

    // Build EA pill list
    list.innerHTML = '';
    data.ex5.forEach(ea => {
      const pill = document.createElement('button');
      pill.type = 'button';
      pill.style.cssText = 'display:flex;align-items:center;justify-content:space-between;padding:0.55rem 0.85rem;background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,0.08);border-radius:9px;cursor:pointer;font-family:inherit;width:100%;text-align:left;transition:all 0.15s';
      pill.onmouseover = () => { pill.style.background='rgba(124,109,250,0.12)'; pill.style.borderColor='rgba(124,109,250,0.4)'; };
      pill.onmouseout  = () => { pill.style.background='rgba(255,255,255,0.04)'; pill.style.borderColor='rgba(255,255,255,0.08)'; };
      pill.innerHTML = `
        <span style="font-size:0.85rem;font-weight:600;color:#e2e8f0">${ea.name}</span>
        ${ea.suggested_set
          ? '<span style="font-size:0.7rem;background:rgba(0,212,170,0.15);color:#00d4aa;padding:2px 8px;border-radius:999px;font-weight:600">.set matched</span>'
          : '<span style="font-size:0.7rem;color:#64748b">no .set matched</span>'
        }
      `;
      pill.onclick = () => autoFillFromEA(ea);
      list.appendChild(pill);
    });

    // Build .set picker
    picker.innerHTML = '<option value="">— pick from detected .set files —</option>';
    data.set.forEach(s => {
      const opt = new Option(s.filename, s.path);
      picker.add(opt);
    });
    picker.style.display = data.set.length ? 'block' : 'none';

    section.style.display = 'block';
  }

  function autoFillFromEA(ea) {
    document.getElementById('new-ea-name').value = ea.name;
    document.getElementById('new-ea-file').value = ea.name;
    if (ea.suggested_set) {
      document.getElementById('new-ea-set').value = ea.suggested_set;
      document.getElementById('set-match-badge').style.display = 'inline';
    } else {
      document.getElementById('new-ea-set').value = '';
      document.getElementById('set-match-badge').style.display = 'none';
    }
    // Scroll to bottom of modal to show form fields
    document.getElementById('add-ea-modal').querySelector('div').scrollTop = 999;
  }

  function onSetPick() {
    const val = document.getElementById('set-picker').value;
    if (val) {
      document.getElementById('new-ea-set').value = val;
      document.getElementById('set-match-badge').style.display = 'inline';
    }
  }

  async function registerNewEA() {
    const name = document.getElementById('new-ea-name').value.trim();
    const file = document.getElementById('new-ea-file').value.trim();
    const set  = document.getElementById('new-ea-set').value.trim();
    const symbol    = document.getElementById('new-ea-symbol').value;
    const timeframe = document.getElementById('new-ea-tf').value;

    if (!name || !set) {
      alert('EA Name and .set file path are required.');
      return;
    }

    try {
      const resp = await fetch('/api/ea/register', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ name, ex5_file: file || name, set_template: set, symbol, timeframe, mode: 'generic' }),
      });
      const result = await resp.json();
      if (result.ok) {
        hideAddEAModal();
        // Add to dropdown immediately without reload
        const sel = document.getElementById('ea_name');
        const existing = [...sel.options].find(o => o.value === name);
        if (!existing) {
          const opt = new Option(name, name);
          sel.add(opt);
        }
        sel.value = name;
        document.getElementById('scan-status').textContent = `"${name}" registered ✓`;
        document.getElementById('scan-status').style.color = '#00d4aa';
        // Reload params for this EA
        if (typeof loadEAParams === 'function') loadEAParams(name);
      } else {
        alert('Error: ' + (result.error || 'Registration failed'));
      }
    } catch(e) {
      alert('Network error: ' + e.message);
    }
  }

  async function loadEAParams(eaName) {
    const grid = document.getElementById('param-grid');
    if (!grid) return;
    grid.innerHTML = '<span style="color:#64748b;font-size:0.82rem">Loading parameters...</span>';
    try {
      const resp = await fetch('/api/ea_params?ea=' + encodeURIComponent(eaName));
      const params = await resp.json();
      if (params.error) { grid.innerHTML = `<span style="color:#ef4444;font-size:0.82rem">${params.error}</span>`; return; }
      if (!params.length) { grid.innerHTML = '<span style="color:#64748b;font-size:0.82rem">No optimizable parameters found in .set file.</span>'; return; }
      grid.innerHTML = params.map(p => `
        <label class="param-check">
          <input type="checkbox" name="selected_params" value="${p.name}" ${p.optimize ? 'checked' : ''}>
          <span title="${p.range || ''}">${p.name.replace('Inp','')}</span>
        </label>
      `).join('');
    } catch(e) {
      grid.innerHTML = `<span style="color:#ef4444;font-size:0.82rem">Error loading params: ${e.message}</span>`;
    }
  }

  // Reload params + symbol/timeframe when EA selection changes
  document.getElementById('ea_name').addEventListener('change', function() {
    loadEAParams(this.value);
  });

  // ── Pre-flight check ──────────────────────────────────────────
  async function runPreflight() {
    const list = document.getElementById('preflight-list');
    const status = document.getElementById('preflight-status');
    if (!list) return;
    try {
      const r = await fetch('/api/preflight');
      const d = await r.json();
      const blocking = d.blocking_count || 0;
      status.textContent = blocking === 0 ? (d.demo_mode ? 'demo mode · ready' : 'all clear · ready') : `${blocking} issue${blocking > 1 ? 's' : ''} to fix`;
      status.style.color = blocking === 0 ? '#10b981' : '#ef4444';
      list.innerHTML = (d.checks || []).map(c => {
        let cls = 'ok', mark = '✓';
        if (!c.ok) {
          // API key is informational, not blocking
          if (c.name && c.name.toLowerCase().includes('api key')) { cls = 'warn'; mark = '!'; }
          else { cls = 'err'; mark = '✗'; }
        }
        return `<div class="pf-row ${cls}">
          <div class="pf-mark">${mark}</div>
          <div><div class="pf-name">${c.name || ''}</div>${c.hint ? `<span class="pf-hint">${c.hint}</span>` : ''}</div>
        </div>`;
      }).join('');
    } catch (e) {
      status.textContent = 'preflight failed';
      status.style.color = '#ef4444';
      list.innerHTML = `<div class="pf-row err"><div class="pf-mark">✗</div><div><div class="pf-name">Could not reach /api/preflight</div><span class="pf-hint">${e.message}</span></div></div>`;
    }
  }
  runPreflight();
  // Re-run preflight when user adds an EA so the "EA registered" check refreshes
  window.addEventListener('focus', runPreflight);

  function toggleAutonomous(btn) {
    const isOn = btn.style.background === 'rgb(79, 70, 229)' || btn.classList.contains('on');
    if (isOn) {
      btn.style.background = 'rgba(255,255,255,0.12)';
      btn.classList.remove('on');
      btn.querySelector('span') && (btn.querySelector('span').style.transform = '');
      document.getElementById('autonomous-controls').style.display = 'none';
      document.getElementById('autonomous-mode-val').value = 'false';
    } else {
      btn.style.background = '#4f46e5';
      btn.classList.add('on');
      document.getElementById('autonomous-controls').style.display = 'block';
      document.getElementById('autonomous-mode-val').value = 'true';
    }
    // Maintain the ::after pseudo-element position via class
    btn.style.setProperty('--toggle-x', isOn ? '0px' : '20px');
  }

  // ── Toast helper for inline validation feedback ────────────────────────
  function showSetupError(msg) {
    let toast = document.getElementById('setup-toast');
    if (!toast) {
      toast = document.createElement('div');
      toast.id = 'setup-toast';
      toast.style.cssText = 'position:fixed;top:20px;right:20px;background:rgba(239,68,68,0.95);color:white;padding:0.8rem 1.2rem;border-radius:8px;font-size:0.85rem;font-weight:600;z-index:9999;box-shadow:0 4px 12px rgba(0,0,0,0.3);max-width:380px;line-height:1.4;';
      document.body.appendChild(toast);
    }
    toast.textContent = msg;
    toast.style.display = 'block';
    clearTimeout(toast._timer);
    toast._timer = setTimeout(() => { toast.style.display = 'none'; }, 5000);
  }

  function validateSetup(data) {
    if (!data.ea_name || !data.ea_name.trim()) {
      return 'Please select an EA before starting.';
    }
    if (!data.symbol || !data.timeframe) {
      return 'Symbol and timeframe are required.';
    }
    const ds = (s) => new Date((s || '').replace(/\./g, '-'));
    const ts = ds(data.train_start), te = ds(data.train_end);
    const vs = ds(data.val_start),   ve = ds(data.val_end);
    if (isNaN(ts) || isNaN(te) || isNaN(vs) || isNaN(ve)) {
      return 'All four dates must be valid (YYYY-MM-DD).';
    }
    if (ts >= te) return 'Training start must come before training end.';
    if (vs >= ve) return 'Validation start must come before validation end.';
    if (vs < te) return 'Validation period should start after the training period (walk-forward).';
    if (data.budget_minutes < 1) return 'Time budget must be at least 1 minute.';
    if (!data.selected_params || data.selected_params.length === 0) {
      return 'Pick at least one parameter to optimize.';
    }
    if (data.autonomous_mode) {
      if (data.autonomous_max_iterations < 1 || data.autonomous_max_iterations > 100) {
        return 'AI max iterations must be between 1 and 100.';
      }
      if (data.target_profit_factor < 1) return 'Target profit factor must be ≥ 1.';
      if (data.target_max_drawdown_pct <= 0 || data.target_max_drawdown_pct > 100) {
        return 'Target max drawdown must be between 0 and 100 (%).';
      }
    }
    return null;  // valid
  }

  document.getElementById('setup-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const btn = document.getElementById('start-btn');
    const restoreBtn = () => {
      btn.disabled = false;
      btn.innerHTML = '<span>⚡</span> Start Optimization';
    };

    const form = e.target;
    const autonomousOn = document.getElementById('autonomous-mode-val').value === 'true';
    const data = {
      ea_name:        form.ea_name.value,
      symbol:         form.symbol.value,
      timeframe:      form.timeframe.value,
      train_start:    form.train_start.value.replace(/-/g, '.'),
      train_end:      form.train_end.value.replace(/-/g, '.'),
      val_start:      form.val_start.value.replace(/-/g, '.'),
      val_end:        form.val_end.value.replace(/-/g, '.'),
      objective:      form.objective.value,
      budget_minutes: parseInt(form.budget_minutes.value),
      selected_params: [...form.querySelectorAll('input[name=selected_params]:checked')]
                         .map(cb => cb.value),
      // Autonomous loop
      autonomous_mode:           autonomousOn,
      autonomous_max_iterations: parseInt(document.getElementById('ai-max-iter').value) || 10,
      target_profit_factor:      parseFloat(document.getElementById('ai-target-pf').value) || 1.5,
      target_max_drawdown_pct:   parseFloat(document.getElementById('ai-target-dd').value) || 20.0,
      target_min_calmar:         parseFloat(document.getElementById('ai-target-calmar').value) || 0.5,
    };

    const validationError = validateSetup(data);
    if (validationError) {
      showSetupError(validationError);
      return;
    }

    btn.disabled = true;
    btn.innerHTML = '<span>⏳</span> Starting...';

    try {
      const resp = await fetch('/api/start', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data),
      });
      const result = await resp.json();
      if (result.ok) {
        window.location.href = '/dashboard';
      } else {
        showSetupError('Could not start: ' + (result.msg || 'Unknown error'));
        restoreBtn();
      }
    } catch(err) {
      showSetupError('Network error: ' + err.message);
      restoreBtn();
    }
  });
</script>
</body>
</html>
