<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Trading Journal</title>
<style>
  body {
    font-family: Arial, sans-serif;
    margin: 20px;
    background: #f4f6f8;
  }
  /* Header Wrapper */
  #headerWrapper {
    max-width: 1100px;
    margin: 0 auto 25px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 25px;
    flex-wrap: wrap;
  }
  #headerWrapper h1 {
    margin: 0;
  }
  #headerWrapper label {
    font-weight: bold;
    font-size: 16px;
    margin-right: 8px;
  }
  #headerWrapper input[type="number"] {
    width: 120px;
    padding: 5px 8px;
    font-size: 16px;
  }
  #actualBalanceWrapper {
    font-weight: bold;
    font-size: 16px;
    background-color: #007bff;
    color: white;
    padding: 6px 12px;
    border-radius: 4px;
  }
  input[disabled] {
    background-color: #e9ecef;
  }
  form {
    background: white;
    padding: 20px 30px;
    border-radius: 8px;
    margin-bottom: 30px;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
    max-width: 1100px;
    margin-left: auto;
    margin-right: auto;
  }
  form .grid-container {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 18px 40px;
    align-items: center;
  }
  form .grid-container div {
    display: flex;
    align-items: center;
  }
  label {
    width: 140px;
    font-weight: bold;
    margin-right: 12px;
    white-space: nowrap;
  }
  input[type="text"],
  input[type="number"],
  input[type="time"],
  input[type="date"],
  select,
  textarea {
    flex: 1;
    padding: 6px 8px;
    font-size: 14px;
    border: 1px solid #ccc;
    border-radius: 4px;
    min-width: 0;
  }
  textarea {
    resize: vertical;
  }
  /* Full width fields: e.g. textareas or wide inputs below */
  .full-width {
    grid-column: 1 / -1;
    margin-top: 10px;
  }
  /* Buttons */
  button {
    background-color: #007bff;
    color: white;
    border:none;
    padding: 10px 16px;
    cursor: pointer;
    border-radius: 4px;
    font-size: 16px;
  }
  button:disabled {
    background-color: #aaa;
    cursor: not-allowed;
  }
  button:hover:not(:disabled) {
    background-color: #0056b3;
  }
  #buttonsWrapper {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    max-width: 1100px;
    margin-left: auto;
    margin-right: auto;
    gap: 10px;
    flex-wrap: wrap;
  }
  /* Table styling */
  table {
    width: 100%;
    border-collapse: collapse;
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
    max-width: 1100px;
    margin-left: auto;
    margin-right: auto;
  }
  th, td {
    text-align: center;
    padding: 8px;
    border-bottom: 1px solid #ddd;
    font-size: 13px;
    vertical-align: middle;
    word-break: break-word;
  }
  th {
    background-color: #007bff;
    color: white;
    position: sticky;
    top: 0;
    z-index: 2;
  }
  tr:hover {
    background-color: #f1f1f1;
  }
  .actions button {
    background-color: #dc3545;
    margin: 0 2px;
    padding: 5px 8px;
    font-size: 12px;
  }
  .actions button.edit {
    background-color: #28a745;
  }
  #clearAllBtn {
    background-color: #6c757d;
  }
  /* Responsive for smaller screens: stack form fields */
  @media (max-width: 700px) {
    form .grid-container {
      grid-template-columns: 1fr;
    }
    label {
      width: 110px;
    }
    #buttonsWrapper {
      flex-direction: column;
      gap: 10px;
    }
    #buttonsWrapper button {
      width: 100%;
    }
    #headerWrapper {
      justify-content: center;
    }
  }
</style>
</head>
<body>

<!-- Header with Balance and Actual Balance display -->
<div id="headerWrapper" aria-label="Account balances">
  <h1>Trading Journal</h1>
  <div>
    <label for="initialBalance">Balance:</label>
    <input type="number" id="initialBalance" min="0" step="100" aria-describedby="balanceDesc"/>
    <div id="balanceDesc" style="font-weight:normal; font-size:12px; color: #555;">Initial account balance</div>
  </div>
  <div id="actualBalanceWrapper" aria-live="polite" title="Initial Balance plus all profits">Actual Balance: $<span id="actualBalance">0.00</span></div>
</div>

<form id="tradeForm" autocomplete="off" aria-label="Add or edit trade">
  <input type="hidden" id="tradeIndex" />

  <div class="grid-container">
    <div>
      <label for="trade">Trade #<sup style="color:red">*</sup></label>
      <input type="number" id="trade" min="1" placeholder="e.g. 1" required aria-required="true" />
    </div>
    <div>
      <label for="emaBias">M15 EMA's Bias</label>
      <select id="emaBias" aria-label="M15 EMA's Bias">
        <option value="">Select</option>
        <option>Uptrend</option>
        <option>Downtrend</option>
        <option>Sideways</option>
      </select>
    </div>

    <div>
      <label for="day">Day (Date)<sup style="color:red">*</sup></label>
      <input type="date" id="day" required aria-required="true" />
    </div>
    <div>
      <label for="time">Time<sup style="color:red">*</sup></label>
      <input type="time" id="time" required aria-required="true" />
    </div>

    <div>
      <label for="symbol">Symbol<sup style="color:red">*</sup></label>
      <input type="text" id="symbol" placeholder="e.g. EURUSD" required aria-required="true" />
    </div>
    <div>
      <label for="session">Session When Open</label>
      <select id="session" aria-label="Session When Open">
        <option value="">Select</option>
        <option>Asia</option>
        <option>London</option>
        <option>New York</option>
        <option>Other</option>
      </select>
    </div>

    <div>
      <label for="risk">Risk %</label>
      <input type="number" id="risk" min="0" step="0.01" placeholder="e.g. 1.5" />
    </div>
    <div>
      <label for="rrr">RRR (Risk Reward Ratio)</label>
      <input type="number" id="rrr" min="0" step="0.1" placeholder="e.g. 2" />
    </div>

    <div>
      <label for="positionSize">Position Size<sup style="color:red">*</sup></label>
      <input type="number" id="positionSize" min="0" step="0.01" placeholder="e.g. 0.5" required aria-required="true" />
    </div>
    <div>
      <label for="mode">Mode<sup style="color:red">*</sup></label>
      <select id="mode" required aria-required="true">
        <option value="">Select</option>
        <option>Buy</option>
        <option>Sell</option>
      </select>
    </div>

    <div>
      <label for="entry">Entry Price<sup style="color:red">*</sup></label>
      <input type="number" id="entry" min="0" step="0.0001" placeholder="e.g. 1.1234" required aria-required="true" />
    </div>
    <div>
      <label for="sl">Stop Loss (SL)</label>
      <input type="number" id="sl" min="0" step="0.0001" placeholder="e.g. 1.1200" />
    </div>

    <div>
      <label for="tp">Take Profit (TP)</label>
      <input type="number" id="tp" min="0" step="0.0001" placeholder="e.g. 1.1300" />
    </div>
    <div>
      <label for="exitType">Exit Type<sup style="color:red">*</sup></label>
      <select id="exitType" required aria-required="true">
        <option value="">Select</option>
        <option value="SL">Stop Loss (SL)</option>
        <option value="TP">Take Profit (TP)</option>
        <option value="Manual">Manual</option>
      </select>
    </div>

    <!-- Exit Price removed -->

    <div>
      <label for="close">Close Price</label>
      <input type="number" id="close" min="0" step="0.0001" placeholder="Only if manual exit" disabled />
    </div>

    <div class="full-width">
      <label for="whyOpen" style="vertical-align: top;">Why Open</label>
      <textarea id="whyOpen" rows="2" placeholder="Explain why you opened this trade"></textarea>
    </div>

    <div class="full-width">
      <label for="feelings" style="vertical-align: top;">Feelings</label>
      <textarea id="feelings" rows="2" placeholder="What were your emotions"></textarea>
    </div>

    <div>
      <label for="closeRrr">Close RRR</label>
      <input type="number" id="closeRrr" min="0" step="0.1" placeholder="Exit RRR" />
    </div>
    <div>
      <label for="closeTime">Close Time</label>
      <input type="time" id="closeTime" />
    </div>

    <div class="full-width">
      <label for="whyCloseManual" style="vertical-align: top;">Why Close if Exit Manual</label>
      <textarea id="whyCloseManual" rows="2" placeholder="Reason for manual exit"></textarea>
    </div>

    <div>
      <label for="profit">Profit<sup style="color:red">*</sup></label>
      <input type="number" id="profit" step="0.01" placeholder="Enter profit" required aria-required="true" aria-describedby="profitDesc" />
      <div id="profitDesc" style="font-weight:normal; font-size:12px; color: #555;">Enter the profit manually</div>
    </div>
    <div>
      <label for="accountReward">Account Reward (%)</label>
      <input type="number" id="accountReward" step="0.0001" placeholder="Calculated automatically" disabled />
    </div>

    <div class="full-width">
      <label for="resultAfterClose" style="vertical-align: top;">Result After Close if Exit Manual</label>
      <textarea id="resultAfterClose" rows="3" placeholder="Notes after trade closes"></textarea>
    </div>
  </div>

  <div id="buttonsWrapper">
    <button type="submit" id="submitBtn">Add Trade</button>
    <button type="button" id="clearAllBtn" title="Clear All Trades">Clear All</button>
    <button type="button" id="exportBtn" title="Export all trades as CSV">Export Trades</button>
    <button type="button" id="statsBtn" title="Go to statistics page">Stats</button>
  </div>
</form>

<table id="tradesTable" aria-label="Trading journal records">
  <thead>
    <tr>
      <th>Trade #</th>
      <th>Day</th>
      <th>Time</th>
      <th>Symbol</th>
      <th>Session</th>
      <th>M15 EMA's Bias</th>
      <th>Risk %</th>
      <th>RRR</th>
      <th>Position Size</th>
      <th>Mode</th>
      <th>Entry</th>
      <th>SL</th>
      <th>TP</th>
      <th>Exit Type</th>
      <th>Close</th>
      <th>Close RRR</th>
      <th>Close Time</th>
      <th>Why Open</th>
      <th>Feelings</th>
      <th>Why Close If Manual</th>
      <th>Profit</th>
      <th>Account Reward (%)</th>
      <th>Result After Close</th>
      <th>Actions</th>
    </tr>
  </thead>
  <tbody>
    <!-- Trades inserted by JS -->
  </tbody>
</table>

<script>
  const tradeForm = document.getElementById('tradeForm');
  const tradesTableBody = document.querySelector('#tradesTable tbody');
  const clearAllBtn = document.getElementById('clearAllBtn');
  const submitBtn = document.getElementById('submitBtn');
  const exportBtn = document.getElementById('exportBtn');
  const statsBtn = document.getElementById('statsBtn');

  const exitTypeEl = document.getElementById('exitType');
  const closePriceEl = document.getElementById('close');
  const sessionEl = document.getElementById('session');
  const timeEl = document.getElementById('time');

  const initialBalanceInput = document.getElementById('initialBalance');
  const actualBalanceSpan = document.getElementById('actualBalance');

  // Store full data: initialBalance and trades array
  let data = {
    initialBalance: 5000,
    trades: []
  };

  let trades = data.trades;

  // Auto-set session based on time input
  function autoSelectSession(timeValue) {
    if(!timeValue) {
      sessionEl.value = "";
      return;
    }
    const [h, m] = timeValue.split(':').map(Number);
    const minutesTotal = h * 60 + m;

    const asiaStart = 1 * 60;
    const asiaEnd = 7 * 60;
    const londonStart = 10 * 60;
    const londonEnd = 12 * 60;
    const nyStart = 15 * 60;
    const nyEnd = 18 * 60;

    if (minutesTotal >= asiaStart && minutesTotal <= asiaEnd) {
      sessionEl.value = "Asia";
    } else if (minutesTotal >= londonStart && minutesTotal <= londonEnd) {
      sessionEl.value = "London";
    } else if (minutesTotal >= nyStart && minutesTotal <= nyEnd) {
      sessionEl.value = "New York";
    } else {
      sessionEl.value = "";
    }
  }

  timeEl.addEventListener('input', e => {
    autoSelectSession(e.target.value);
  });

  // Enable or disable Close Price input based on Exit Type
  exitTypeEl.addEventListener('change', () => {
    if(exitTypeEl.value === 'Manual') {
      closePriceEl.disabled = false;
      closePriceEl.required = true;
    } else {
      closePriceEl.disabled = true;
      closePriceEl.value = '';
      closePriceEl.required = false;
    }
  });

  window.addEventListener('DOMContentLoaded', () => {
    if(exitTypeEl.value === 'Manual') {
      closePriceEl.disabled = false;
      closePriceEl.required = true;
    } else {
      closePriceEl.disabled = true;
      closePriceEl.required = false;
    }
  });

  // When initial balance input changes - update server
  initialBalanceInput.addEventListener('input', async () => {
    let val = Number(initialBalanceInput.value);
    if (isNaN(val) || val < 0) val = 5000;
    data.initialBalance = val;
    try {
      const res = await fetch('/save.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
      });
      if (!res.ok) throw new Error("Network error saving initial balance.");
      const json = await res.json();
      if(json.status !== 'saved') throw new Error("Server error saving initial balance.");
      updateAccountRewardForAllTrades();
      updateActualBalanceDisplay();
      renderTrades();
    } catch(e) {
      alert("Error saving initial balance: " + e.message);
    }
  });

  // Calculate account reward % from initial balance
  function calculateAccountReward(profit) {
    if (profit === null || profit === undefined || isNaN(profit)) return '';
    if(data.initialBalance === 0) return '';
    return ((profit / data.initialBalance) * 100).toFixed(4);
  }

  // Update actual balance display (initial + sum of profits)
  function updateActualBalanceDisplay() {
    const totalProfit = data.trades.reduce((acc, trade) => acc + (trade.profit || 0), 0);
    const actual = data.initialBalance + totalProfit;
    actualBalanceSpan.textContent = actual.toFixed(2);
  }

  // Update account reward field for all trades
  function updateAccountRewardForAllTrades() {
    data.trades.forEach(trade => {
      trade.accountReward = calculateAccountReward(trade.profit);
    });
  }

  // Render trade table rows
  function renderTrades() {
    tradesTableBody.innerHTML = '';
    if(data.trades.length === 0) {
      const tr = document.createElement('tr');
      const td = document.createElement('td');
      td.colSpan = 24; // one less due to removed exit price field
      td.style.textAlign = 'center';
      td.textContent = 'No trades recorded yet.';
      tr.appendChild(td);
      tradesTableBody.appendChild(tr);
      updateActualBalanceDisplay();
      return;
    }

    data.trades.forEach((trade, index) => {
      const tr = document.createElement('tr');

      const fields = [
        trade.trade,
        trade.day,
        trade.time,
        trade.symbol,
        trade.session,
        trade.emaBias,
        trade.risk,
        trade.rrr,
        trade.positionSize,
        trade.mode,
        trade.entry,
        trade.sl,
        trade.tp,
        trade.exitType,
        trade.close,
        trade.closeRrr,
        trade.closeTime,
        trade.whyOpen,
        trade.feelings,
        trade.whyCloseManual,
        trade.profit,
        trade.accountReward,
        trade.resultAfterClose,
      ];

      fields.forEach(field => {
        const td = document.createElement('td');
        td.textContent = (field === undefined || field === null) ? '' : field;
        td.title = td.textContent;
        tr.appendChild(td);
      });

      // Profit column color coding
      const profitTd = tr.children[19];
      if(profitTd && profitTd.textContent !== '') {
        const val = Number(profitTd.textContent);
        profitTd.style.color = val >= 0 ? 'green' : 'red';
      }

      const actionsTd = document.createElement('td');
      actionsTd.className = 'actions';

      const editBtn = document.createElement('button');
      editBtn.textContent = 'Edit';
      editBtn.className = 'edit';
      editBtn.type = 'button';
      editBtn.title = "Edit trade";
      editBtn.addEventListener('click', () => {
        populateFormForEdit(index);
        window.scrollTo(0, 0);
      });

      const delBtn = document.createElement('button');
      delBtn.textContent = 'Delete';
      delBtn.type = 'button';
      delBtn.title = "Delete trade";
      delBtn.addEventListener('click', async () => {
        if(confirm(`Are you sure you want to delete trade #${trade.trade}?`)) {
          data.trades.splice(index, 1);
          try {
            const res = await fetch('/save.php', {
              method: 'POST',
              headers: {'Content-Type': 'application/json'},
              body: JSON.stringify(data)
            });
            if(!res.ok) throw new Error('Network error');
            const json = await res.json();
            if(json.status === 'saved') {
              alert('Trade deleted.');
              updateAccountRewardForAllTrades();
              updateActualBalanceDisplay();
              renderTrades();
            } else {
              alert('Failed to save trades on server after deletion.');
            }
          } catch(e) {
            alert('Error deleting trade: ' + e.message);
          }
        }
      });

      actionsTd.appendChild(editBtn);
      actionsTd.appendChild(delBtn);
      tr.appendChild(actionsTd);

      tradesTableBody.appendChild(tr);
    });
    updateActualBalanceDisplay();
  }

  // Fill form for editing a trade
  function populateFormForEdit(index) {
    const trade = data.trades[index];
    document.getElementById('tradeIndex').value = index;

    document.getElementById('trade').value = trade.trade || '';
    document.getElementById('day').value = trade.day || '';
    document.getElementById('time').value = trade.time || '';
    document.getElementById('symbol').value = trade.symbol || '';
    document.getElementById('session').value = trade.session || '';
    document.getElementById('emaBias').value = trade.emaBias || '';
    document.getElementById('risk').value = trade.risk || '';
    document.getElementById('rrr').value = trade.rrr || '';
    document.getElementById('positionSize').value = trade.positionSize || '';
    document.getElementById('mode').value = trade.mode || '';
    document.getElementById('entry').value = trade.entry || '';
    document.getElementById('sl').value = trade.sl || '';
    document.getElementById('tp').value = trade.tp || '';
    document.getElementById('exitType').value = trade.exitType || '';
    document.getElementById('close').value = trade.close || '';
    document.getElementById('closeRrr').value = trade.closeRrr || '';
    document.getElementById('closeTime').value = trade.closeTime || '';
    document.getElementById('whyOpen').value = trade.whyOpen || '';
    document.getElementById('feelings').value = trade.feelings || '';
    document.getElementById('whyCloseManual').value = trade.whyCloseManual || '';
    document.getElementById('profit').value = trade.profit || '';
    document.getElementById('accountReward').value = trade.accountReward || '';
    document.getElementById('resultAfterClose').value = trade.resultAfterClose || '';

    closePriceEl.disabled = trade.exitType === 'Manual' ? false : true;
    closePriceEl.required = trade.exitType === 'Manual';

    submitBtn.textContent = 'Update Trade';
  }

  // Form submit handler for add/update
  tradeForm.addEventListener('submit', async e => {
    e.preventDefault();

    function getNumberValue(id) {
      const v = document.getElementById(id).value;
      return v === '' ? null : Number(v);
    }

    // Validate required fields (without Exit Price since removed)
    const requiredFields = [
      {id: 'trade', name: 'Trade #'},
      {id: 'day', name: 'Day (Date)'},
      {id: 'time', name: 'Time'},
      {id: 'symbol', name: 'Symbol'},
      {id: 'positionSize', name: 'Position Size'},
      {id: 'mode', name: 'Mode'},
      {id: 'entry', name: 'Entry Price'},
      {id: 'exitType', name: 'Exit Type'},
      {id: 'profit', name: 'Profit'},
    ];

    for (const field of requiredFields) {
      const val = document.getElementById(field.id).value;
      if (!val || val.trim() === '') {
        alert(`Please fill out required field: ${field.name}`);
        return;
      }
    }

    if(exitTypeEl.value === 'Manual' && (!closePriceEl.value || closePriceEl.value.trim() === '')) {
      alert("Close Price is required for Manual exit type.");
      return;
    }

    // Validate numeric fields
    const numberFields = ['risk','rrr','positionSize','entry','sl','tp','close','closeRrr','profit'];
    for (const nf of numberFields) {
      const val = document.getElementById(nf).value;
      if(val) {
        const num = Number(val);
        if(isNaN(num)) {
          alert(`Field ${nf} must be a valid number.`);
          return;
        }
      }
    }

    let tradeData = {
      trade: getNumberValue('trade'),
      day: document.getElementById('day').value || '',
      time: document.getElementById('time').value || '',
      symbol: document.getElementById('symbol').value.trim() || '',
      session: document.getElementById('session').value,
      emaBias: document.getElementById('emaBias').value,
      risk: getNumberValue('risk'),
      rrr: getNumberValue('rrr'),
      positionSize: getNumberValue('positionSize'),
      mode: document.getElementById('mode').value,
      entry: getNumberValue('entry'),
      sl: getNumberValue('sl'),
      tp: getNumberValue('tp'),
      exitType: document.getElementById('exitType').value,
      close: getNumberValue('close'),
      closeRrr: getNumberValue('closeRrr'),
      closeTime: document.getElementById('closeTime').value || '',
      whyOpen: document.getElementById('whyOpen').value.trim() || '',
      feelings: document.getElementById('feelings').value.trim() || '',
      whyCloseManual: document.getElementById('whyCloseManual').value.trim() || '',
      profit: getNumberValue('profit'),
      accountReward: '',
      resultAfterClose: document.getElementById('resultAfterClose').value.trim() || '',
    };

    if (tradeData.profit === null || isNaN(tradeData.profit)) {
      alert("Please enter a valid profit value.");
      return;
    }

    tradeData.accountReward = calculateAccountReward(tradeData.profit);

    const index = document.getElementById('tradeIndex').value;
    if(index === '') {
      data.trades.push(tradeData);
    } else {
      data.trades[index] = tradeData;
    }

    data.trades.sort((a, b) => (a.trade || 0) - (b.trade || 0));

    try {
      const response = await fetch('/save.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
      });
      if (!response.ok) throw new Error('Network response was not ok');
      const result = await response.json();

      if(result.status === 'saved') {
        alert('Trade saved successfully.');
        tradeForm.reset();
        submitBtn.textContent = 'Add Trade';
        document.getElementById('tradeIndex').value = '';

        updateAccountRewardForAllTrades();
        updateActualBalanceDisplay();
        renderTrades();
      } else {
        alert('Failed to save trades on server.');
      }
    } catch (err) {
      alert('Error saving trades: ' + err.message);
    }
  });

  clearAllBtn.addEventListener('click', async () => {
    if(confirm('Are you sure you want to delete all trades? This action cannot be undone.')) {
      data.trades = [];
      try {
        const response = await fetch('/save.php', {
          method: 'POST',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify(data)
        });
        if(!response.ok) throw new Error("Network error");
        const result = await response.json();
        if(result.status === 'saved') {
          alert('All trades cleared.');
          updateAccountRewardForAllTrades();
          updateActualBalanceDisplay();
          renderTrades();
        } else {
          alert('Failed to clear trades on server.');
        }
      } catch(e) {
        alert('Error clearing trades: ' + e.message);
      }
    }
  });

  // Helper to escape CSV values properly
  function csvEscape(value) {
    if (value === null || value === undefined) return '';
    const str = String(value);
    if(str.includes('"') || str.includes(',') || str.includes('\n') || str.includes('\r')) {
      return `"${str.replace(/"/g, '""')}"`;
    }
    return str;
  }

  // Export trades as CSV
  function exportTradesToCSV() {
    if (data.trades.length === 0) {
      alert('No trades to export.');
      return;
    }
    const headers = [
      "Trade #",
      "Day",
      "Time",
      "Symbol",
      "Session",
      "M15 EMA's Bias",
      "Risk %",
      "RRR",
      "Position Size",
      "Mode",
      "Entry",
      "SL",
      "TP",
      "Exit Type",
      "Close",
      "Close RRR",
      "Close Time",
      "Why Open",
      "Feelings",
      "Why Close If Manual",
      "Profit",
      "Account Reward (%)",
      "Result After Close"
    ];

    let csvContent = headers.map(csvEscape).join(",") + "\r\n";

    data.trades.forEach(trade => {
      const row = [
        trade.trade,
        trade.day,
        trade.time,
        trade.symbol,
        trade.session,
        trade.emaBias,
        trade.risk,
        trade.rrr,
        trade.positionSize,
        trade.mode,
        trade.entry,
        trade.sl,
        trade.tp,
        trade.exitType,
        trade.close,
        trade.closeRrr,
        trade.closeTime,
        trade.whyOpen,
        trade.feelings,
        trade.whyCloseManual,
        trade.profit,
        trade.accountReward,
        trade.resultAfterClose
      ].map(csvEscape);
      csvContent += row.join(",") + "\r\n";
    });

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);

    const a = document.createElement('a');
    a.href = url;
    a.download = 'trades_export.csv';

    document.body.appendChild(a);
    a.click();
    setTimeout(() => {
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    }, 0);
  }

  exportBtn.addEventListener('click', exportTradesToCSV);

  statsBtn.addEventListener('click', () => {
    window.location.href = 'stats.htm';
  });

  // Load data (initialBalance + trades) from server on page load
  async function loadDataFromServer() {
    try {
      const response = await fetch('/load.php');
      if (!response.ok) throw new Error('Network error loading data');
      data = await response.json();
      if(!data.initialBalance) data.initialBalance = 5000;
      if(!Array.isArray(data.trades)) data.trades = [];
      trades = data.trades;

      initialBalanceInput.value = data.initialBalance.toFixed(2);
      updateAccountRewardForAllTrades();
      updateActualBalanceDisplay();
      renderTrades();
    } catch (e) {
      alert('Failed to load data from server: ' + e.message);
      data = { initialBalance: 5000, trades: [] };
      trades = [];
      initialBalanceInput.value = data.initialBalance.toFixed(2);
      renderTrades();
    }
  }

  window.addEventListener('DOMContentLoaded', loadDataFromServer);
</script>

</body>
</html>