<!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: 20px;
  }
  #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;
  }
  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;
  }
  /* 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%;
    }
  }
</style>
</head>
<body>

<!-- Header with Balance input -->
<div id="headerWrapper">
  <h1>Trading Journal</h1>
  <div>
    <label for="initialBalance">Balance:</label>
    <input type="number" id="initialBalance" min="0" step="100" />
  </div>
</div>

<form id="tradeForm" autocomplete="off">
  <input type="hidden" id="tradeIndex" />

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

    <div>
      <label for="day">Day (Date)</label>
      <input type="date" id="day" />
    </div>
    <div>
      <label for="time">Time</label>
      <input type="time" id="time" />
    </div>

    <div>
      <label for="symbol">Symbol</label>
      <input type="text" id="symbol" placeholder="e.g. EURUSD" />
    </div>
    <div>
      <label for="session">Session When Open</label>
      <select id="session">
        <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</label>
      <input type="number" id="positionSize" min="0" step="0.01" placeholder="e.g. 0.5" />
    </div>
    <div>
      <label for="mode">Mode</label>
      <select id="mode">
        <option value="">Select</option>
        <option>Buy</option>
        <option>Sell</option>
      </select>
    </div>

    <div>
      <label for="entry">Entry Price</label>
      <input type="number" id="entry" min="0" step="0.0001" placeholder="e.g. 1.1234" />
    </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</label>
      <select id="exitType">
        <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>

    <div>
      <label for="exit">Exit Price</label>
      <input type="number" id="exit" min="0" step="0.0001" placeholder="Price exited at" />
    </div>
    <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</label>
      <input type="number" id="profit" step="0.01" placeholder="e.g. 25.50" />
    </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>
  </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>Exit</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 exitTypeEl = document.getElementById('exitType');
  const closePriceEl = document.getElementById('close');
  const sessionEl = document.getElementById('session');
  const timeEl = document.getElementById('time');

  const initialBalanceInput = document.getElementById('initialBalance');
  let initialBalance = Number(localStorage.getItem('initialBalance')) || 5000;
  initialBalanceInput.value = initialBalance;

  // Load trades from localStorage or start empty array
  let trades = JSON.parse(localStorage.getItem('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;
    } else {
      closePriceEl.disabled = true;
      closePriceEl.value = '';
    }
  });

  // On load, ensure correct Close Price input state if editing
  window.addEventListener('DOMContentLoaded', () => {
    if(exitTypeEl.value === 'Manual') {
      closePriceEl.disabled = false;
    } else {
      closePriceEl.disabled = true;
    }
  });

  // Update initial balance when user changes input
  initialBalanceInput.addEventListener('input', () => {
    let val = Number(initialBalanceInput.value);
    if (isNaN(val) || val <= 0) {
      val = 5000;
    }
    initialBalance = val;
    localStorage.setItem('initialBalance', initialBalance);
    updateAccountRewardForAllTrades();
    renderTrades();
  });

  // Calculate Account Reward % (profit relative to initial balance), 4 decimals
  function calculateAccountReward(profit) {
    if (profit === null || profit === undefined || isNaN(profit)) return '';
    if(initialBalance === 0) return '';
    return ((profit / initialBalance) * 100).toFixed(4);
  }

  // Update accountReward for each trade in trades array
  function updateAccountRewardForAllTrades() {
    trades.forEach(trade => {
      trade.accountReward = calculateAccountReward(trade.profit);
    });
  }

  // Call once on load
  updateAccountRewardForAllTrades();

  // Render the trades table rows
  function renderTrades() {
    tradesTableBody.innerHTML = '';
    if(trades.length === 0) {
      const tr = document.createElement('tr');
      const td = document.createElement('td');
      td.colSpan = 25;
      td.style.textAlign = 'center';
      td.textContent = 'No trades recorded yet.';
      tr.appendChild(td);
      tradesTableBody.appendChild(tr);
      return;
    }
    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.exit,
        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);
      });

      // Color code profit column: green positive, red negative
      const profitTd = tr.children[20];
      if(profitTd && profitTd.textContent !== '') {
        const profitVal = Number(profitTd.textContent);
        profitTd.style.color = profitVal >= 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', () => {
        if(confirm(`Are you sure you want to delete trade #${trade.trade}?`)) {
          trades.splice(index, 1);
          saveAndRender();
        }
      });

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

      tradesTableBody.appendChild(tr);
    });
  }

  // Save to localStorage and render
  function saveAndRender() {
    localStorage.setItem('trades', JSON.stringify(trades));
    renderTrades();
    tradeForm.reset();
    submitBtn.textContent = 'Add Trade';
    document.getElementById('tradeIndex').value = '';
    closePriceEl.disabled = true;

    // Reset session auto set based on time (cleared)
    sessionEl.value = "";
    // Re-set initialBalance input (should already be set)
    initialBalanceInput.value = initialBalance;
  }

  function populateFormForEdit(index) {
    const trade = 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('exit').value = trade.exit || '';
    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 || '';

    // Set Close Price enabled state according to exitType
    closePriceEl.disabled = trade.exitType === 'Manual' ? false : true;

    submitBtn.textContent = 'Update Trade';
  }

  tradeForm.addEventListener('submit', e => {
    e.preventDefault();

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

    const 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,
      exit: getNumberValue('exit'),
      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: calculateAccountReward(getNumberValue('profit')),
      resultAfterClose: document.getElementById('resultAfterClose').value.trim() || '',
    };

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

    saveAndRender();
  });

  clearAllBtn.addEventListener('click', () => {
    if(confirm('Are you sure you want to delete all trades? This action cannot be undone.')) {
      trades = [];
      saveAndRender();
    }
  });

  // Helper to escape CSV values properly (quote if needed)
  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 (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",
      "Exit",
      "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";

    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.exit,
        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);

  renderTrades();
</script>

</body>
</html>