RR Tracker v6

RR tracker with cool features

// ==UserScript==
// @name         RR Tracker v6
// @namespace    https://greasyfork.org/users/1493252
// @version      6 // *NEW 2 fingers Drag Mechanics*
// @description RR tracker with cool features
//###Your Torn RR Tracker: Quick Guide
//###Auto-Tracking
//###Just open Russian Roulette, and your tracker starts automatically. It records every win and loss, showing your profit, win rate, and streaks.
//###Panel Controls
//###* Drag: Click and drag the ☰ icon to move the panel anywhere you like.
//###* Collapse/Expand: Click the ► (or ▪) icon to shrink or expand the panel.
//###* Hide/Show: If Auto-Hide is on in settings, the tracker hides when you leave RR and reappears when you return.
//###Settings (⚙️ icon)
//###* Panel Opacity: Adjust how see-through the panel is.
//###* Profit/Loss Alerts: Set targets to be notified when you hit a certain profit or loss.
//###* Mini-Bar Count: Choose how many recent games show in the collapsed view.
//###* Reset Data: Clear all your tracked stats and profit.

// @match        https://www.torn.com/page.php?sid=russianRoulette*
// @grant        none
// @run-at       document-idle
// @license      MIT
// ==/UserScript==

(function waitUntilReady() {
  const PANEL_ID      = 'rr-tracker-panel';
  const STORAGE       = 'torn_rr_tracker_results';
  const PROFIT_STORAGE = 'torn_rr_total_profit';
  const POS_KEY       = 'rr_panelPos';
  const COLLAPSE_KEY  = 'rr_panelCollapsed';
  const AUTOHIDE_KEY  = 'rr_autoHide';
  const MAX_DISPLAY_KEY = 'rr_maxDisplayMatches';

  const OPACITY_KEY   = 'rr_panelOpacity';
  const PROFIT_TARGET_KEY      = 'rr_profitTarget';
  const LOSS_LIMIT_KEY         = 'rr_lossLimit';
  const ALERT_SHOWN_PROFIT_KEY = 'rr_alertShownProfit';
  const ALERT_SHOWN_LOSS_KEY   = 'rr_alertShownLoss';
  const MINI_BAR_COUNT_KEY = 'rr_miniBarCount';

  // NEW: Two-Finger Dragging Variables
  let isTwoFingerDragging = false; // Flag to indicate if two-finger dragging is active
  let initialTouchMidX = 0;
  let initialTouchMidY = 0;
  let initialPanelX = 0;
  let initialPanelY = 0;


  if (document.getElementById(PANEL_ID)) return;

  if (!document.body.innerText.includes('Password') &&
      !document.body.innerText.includes('POT MONEY')) {
    return setTimeout(waitUntilReady, 200);
  }

  let lastPot      = 0;
  let roundActive  = true;
  let hasTracked   = false;
  let results      = JSON.parse(localStorage.getItem(STORAGE) || '[]');
  let totalProfit  = parseFloat(localStorage.getItem(PROFIT_STORAGE) || '0');
  let collapsed    = JSON.parse(localStorage.getItem(COLLAPSE_KEY) || 'false');
  let autoHide     = JSON.parse(localStorage.getItem(AUTOHIDE_KEY) || 'true');
  let showSettings = false;

  let maxDisplayMatches = parseInt(localStorage.getItem(MAX_DISPLAY_KEY) || '100', 10);
  if (isNaN(maxDisplayMatches) || maxDisplayMatches < 1) {
      maxDisplayMatches = 100;
      localStorage.setItem(MAX_DISPLAY_KEY, maxDisplayMatches.toString());
  }

  let currentOpacity  = parseFloat(localStorage.getItem(OPACITY_KEY) || '0.6');
  if (isNaN(currentOpacity) || currentOpacity < 0.1 || currentOpacity > 1.0) {
      currentOpacity = 0.6;
      localStorage.setItem(OPACITY_KEY, currentOpacity.toString());
  }

  let profitTarget = parseFloat(localStorage.getItem(PROFIT_TARGET_KEY) || '0');
  let lossLimit    = parseFloat(localStorage.getItem(LOSS_LIMIT_KEY) || '0');
  let alertShownProfit = JSON.parse(localStorage.getItem(ALERT_SHOWN_PROFIT_KEY) || 'false');
  // Corrected localStorage key here
  let alertShownLoss   = JSON.parse(localStorage.getItem(ALERT_SHOWN_LOSS_KEY) || 'false');


  let miniBarCount = parseInt(localStorage.getItem(MINI_BAR_COUNT_KEY) || '10', 10);
  if (isNaN(miniBarCount) || miniBarCount < 1 || miniBarCount > 50) {
      miniBarCount = 10;
      localStorage.setItem(MINI_BAR_COUNT_KEY, miniBarCount.toString());
  }


  const panel = document.createElement('div');
  panel.id = PANEL_ID;
  Object.assign(panel.style, {
    position:      'fixed',
    top:           '12px',
    left:          '12px',
    background:    `rgba(0,0,0,${currentOpacity})`,
    color:         '#fff',
    fontFamily:    'monospace',
    fontSize:      '14px',
    padding:       '36px 12px 12px',
    borderRadius:  '10px',
    boxShadow:     '0 0 12px rgba(255,0,0,0.3)',
    zIndex:        '9999999',
    userSelect:    'none',
    display:       'flex',
    flexDirection: 'column',
    gap:           '8px',
    minWidth:      '140px'
  });
  document.body.appendChild(panel);

  try {
    const pos = JSON.parse(localStorage.getItem(POS_KEY) || '{}');
    if (pos.top && pos.left) {
      panel.style.top  = pos.top;
      panel.style.left = pos.left;
    }
  } catch {}

  const alertMessageDiv = document.createElement('div');
  alertMessageDiv.id = 'rr-alert-message';
  Object.assign(alertMessageDiv.style, {
      display:         'none',
      padding:         '8px',
      marginBottom:    '8px',
      borderRadius:    '6px',
      textAlign:       'center',
      fontWeight:      'bold',
      fontSize:        '16px',
      color:           'white',
      cursor:          'pointer',
      border:          '1px solid transparent',
      transition:      'background-color 0.3s, border-color 0.3s'
  });
  panel.appendChild(alertMessageDiv);


  const miniBar = document.createElement('div');
  Object.assign(miniBar.style, {
    display:  'none',
    flexWrap: 'wrap',
    gap:      '2px',
    padding:  '4px 0'
  });
  panel.appendChild(miniBar);

  const profitMini = document.createElement('div');
  Object.assign(profitMini.style, {
    display:    'none',
    fontSize:   '14px',
    fontFamily: 'monospace',
    margin:     '2px 0'
  });
  panel.appendChild(profitMini);

  const statusDiv = document.createElement('div');
  Object.assign(statusDiv.style, {
    position: 'absolute', top: '8px', left: '8px',
    width:    '20px',    height: '20px',
    fontSize: '18px',    cursor: 'pointer',
    color:    'rgba(255,255,255,0.7)'
  });
  panel.appendChild(statusDiv);

  const dragHandle = document.createElement('div');
  dragHandle.textContent = '☰';
  Object.assign(dragHandle.style, {
    position:    'absolute',
    top:         '8px',
    right:       '8px',
    width:       '20px',
    height:      '20px',
    fontSize:    '18px',
    cursor:      'move',
    color:       'rgba(255,255,255,0.7)',
    touchAction: 'none' // Prevent default touch actions on this handle
  });
  panel.appendChild(dragHandle);

  const statsGroup = document.createElement('div');
  Object.assign(statsGroup.style, {
    display:       'flex',
    flexDirection: 'column',
    gap:           '4px'
  });
  panel.appendChild(statsGroup);

  const profitDiv  = document.createElement('div');
  const winrateDiv = document.createElement('div');
  const streakDiv  = document.createElement('div');
  statsGroup.append(profitDiv, winrateDiv, streakDiv);

  const resultsContainer = document.createElement('div');
  Object.assign(resultsContainer.style, {
    maxHeight: '140px',
    overflowY: 'auto',
    marginTop: '4px'
  });
  statsGroup.appendChild(resultsContainer);

  const settingsPanel = document.createElement('div');
  Object.assign(settingsPanel.style, {
    display:       'none',
    flexDirection: 'column',
    gap:           '8px',
    padding:       '12px 0'
  });
  panel.appendChild(settingsPanel);

  const settingsTitle = document.createElement('div');
  settingsTitle.textContent = 'Settings';
  Object.assign(settingsTitle.style, {
      fontSize: '16px',
      fontWeight: 'bold',
      marginBottom: '4px'
  });
  settingsPanel.appendChild(settingsTitle);

  const backButton = document.createElement('button');
  backButton.textContent = '← Back';
  Object.assign(backButton.style, {
    alignSelf:   'flex-start',
    background:  'rgba(255,255,255,0.1)',
    color:       '#fff',
    border:      'none',
    borderRadius:'6px',
    padding:     '4px 8px',
    cursor:      'pointer',
    marginBottom: '8px'
  });
  backButton.onmouseenter = () => backButton.style.background = 'rgba(255,255,255,0.2)';
  backButton.onmouseleave = () => backButton.style.background = 'rgba(255,255,255,0.1)';
  backButton.onclick = () => {
      showSettings = false;
      refreshAll();
  };
  settingsPanel.appendChild(backButton);

  const maxMatchesSettingDiv = document.createElement('div');
  Object.assign(maxMatchesSettingDiv.style, {
      display: 'flex',
      alignItems: 'center',
      gap: '8px',
      marginBottom: '8px'
  });
  const maxMatchesLabel = document.createElement('label');
  maxMatchesLabel.textContent = 'Max Matches Displayed:';
  maxMatchesLabel.htmlFor = 'max-matches-input';
  Object.assign(maxMatchesLabel.style, { flexShrink: '0' });

  const maxMatchesInput = document.createElement('input');
  maxMatchesInput.type = 'number';
  maxMatchesInput.id = 'max-matches-input';
  maxMatchesInput.min = '1';
  maxMatchesInput.max = '500';
  maxMatchesInput.value = maxDisplayMatches;
  Object.assign(maxMatchesInput.style, {
      width: '60px',
      padding: '4px',
      border: '1px solid #555',
      borderRadius: '4px',
      background: 'rgba(255,255,255,0.1)',
      color: '#fff'
  });
  maxMatchesInput.onchange = () => {
      let newValue = parseInt(maxMatchesInput.value, 10);
      if (isNaN(newValue) || newValue < 1) {
          newValue = 1;
      }
      if (newValue > 500) newValue = 500;
      maxDisplayMatches = newValue;
      maxMatchesInput.value = maxDisplayMatches;
      localStorage.setItem(MAX_DISPLAY_KEY, maxDisplayMatches.toString());
      while (results.length > maxDisplayMatches) {
          results.pop();
      }
      saveResults();
      refreshAll();
  };
  maxMatchesSettingDiv.append(maxMatchesLabel, maxMatchesInput);
  settingsPanel.appendChild(maxMatchesSettingDiv);

  const transparencySettingDiv = document.createElement('div');
  Object.assign(transparencySettingDiv.style, {
      display: 'flex',
      alignItems: 'center',
      gap: '8px',
      marginBottom: '8px'
  });
  const transparencyLabel = document.createElement('label');
  transparencyLabel.textContent = 'Panel Opacity:';
  transparencyLabel.htmlFor = 'transparency-slider';
  Object.assign(transparencyLabel.style, { flexShrink: '0' });

  const transparencySlider = document.createElement('input');
  transparencySlider.type = 'range';
  transparencySlider.id = 'transparency-slider';
  transparencySlider.min = '0.1';
  transparencySlider.max = '1.0';
  transparencySlider.step = '0.05';
  transparencySlider.value = currentOpacity;
  Object.assign(transparencySlider.style, {
      width: '100px',
      padding: '4px',
      border: 'none',
      background: 'transparent',
      cursor: 'pointer'
  });

  transparencySlider.oninput = () => {
      currentOpacity = parseFloat(transparencySlider.value);
      panel.style.background = `rgba(0,0,0,${currentOpacity})`;
      localStorage.setItem(OPACITY_KEY, currentOpacity.toString());
  };

  transparencySettingDiv.append(transparencyLabel, transparencySlider);
  settingsPanel.appendChild(transparencySettingDiv);

  const profitTargetSettingDiv = document.createElement('div');
  Object.assign(profitTargetSettingDiv.style, {
      display: 'flex',
      alignItems: 'center',
      gap: '8px',
      marginBottom: '8px'
  });
  const profitTargetLabel = document.createElement('label');
  profitTargetLabel.textContent = 'Profit Target ($):';
  profitTargetLabel.htmlFor = 'profit-target-input';
  Object.assign(profitTargetLabel.style, { flexShrink: '0' });

  const profitTargetInput = document.createElement('input');
  profitTargetInput.type = 'number';
  profitTargetInput.id = 'profit-target-input';
  profitTargetInput.min = '0';
  profitTargetInput.value = profitTarget;
  Object.assign(profitTargetInput.style, {
      width: '80px',
      padding: '4px',
      border: '1px solid #555',
      borderRadius: '4px',
      background: 'rgba(255,255,255,0.1)',
      color: '#fff'
  });
  profitTargetInput.onchange = () => {
      let newValue = parseInt(profitTargetInput.value, 10);
      if (isNaN(newValue) || newValue < 0) newValue = 0;
      profitTarget = newValue;
      profitTargetInput.value = profitTarget;
      localStorage.setItem(PROFIT_TARGET_KEY, profitTarget.toString());
      alertShownProfit = false;
      localStorage.setItem(ALERT_SHOWN_PROFIT_KEY, 'false');
      refreshAll();
  };
  profitTargetSettingDiv.append(profitTargetLabel, profitTargetInput);
  settingsPanel.appendChild(profitTargetSettingDiv);


  const lossLimitSettingDiv = document.createElement('div');
  Object.assign(lossLimitSettingDiv.style, {
      display: 'flex',
      alignItems: 'center',
      gap: '8px',
      marginBottom: '8px'
  });
  const lossLimitLabel = document.createElement('label');
  lossLimitLabel.textContent = 'Loss Limit ($):';
  lossLimitLabel.htmlFor = 'loss-limit-input';
  Object.assign(lossLimitLabel.style, { flexShrink: '0' });

  const lossLimitInput = document.createElement('input');
  lossLimitInput.type = 'number';
  lossLimitInput.id = 'loss-limit-input';
  lossLimitInput.min = '0';
  lossLimitInput.value = lossLimit;
  Object.assign(lossLimitInput.style, {
      width: '80px',
      padding: '4px',
      border: '1px solid #555',
      borderRadius: '4px',
      background: 'rgba(255,255,255,0.1)',
      color: '#fff'
  });
  lossLimitInput.onchange = () => {
      let newValue = parseInt(lossLimitInput.value, 10);
      if (isNaN(newValue) || newValue < 0) newValue = 0;
      lossLimit = newValue;
      lossLimitInput.value = lossLimit;
      localStorage.setItem(LOSS_LIMIT_KEY, lossLimit.toString());
      alertShownLoss = false;
      localStorage.setItem(ALERT_SHOWN_LOSS_KEY, 'false');
      refreshAll();
  };
  lossLimitSettingDiv.append(lossLimitLabel, lossLimitInput);
  settingsPanel.appendChild(lossLimitSettingDiv);

  const clearAlertsBtn = document.createElement('button');
  clearAlertsBtn.textContent = '✔️ Clear Alerts';
  Object.assign(clearAlertsBtn.style, {
    alignSelf:   'flex-start',
    background:  'rgba(255,255,255,0.1)',
    color:       '#fff',
    border:      'none',
    borderRadius:'6px',
    padding:     '4px 8px',
    cursor:      'pointer',
    marginTop:   '4px'
  });
  clearAlertsBtn.onmouseenter = () => clearAlertsBtn.style.background = 'rgba(255,255,255,0.2)';
  clearAlertsBtn.onmouseleave = () => clearAlertsBtn.style.background = 'rgba(255,255,255,0.1)';
  clearAlertsBtn.onclick = () => {
      alertShownProfit = false;
      alertShownLoss = false;
      localStorage.setItem(ALERT_SHOWN_PROFIT_KEY, 'false');
      localStorage.setItem(ALERT_SHOWN_LOSS_KEY, 'false');
      alertMessageDiv.style.display = 'none';
      refreshAll();
  };
  settingsPanel.appendChild(clearAlertsBtn);

  const miniBarCountSettingDiv = document.createElement('div');
  Object.assign(miniBarCountSettingDiv.style, {
      display: 'flex',
      alignItems: 'center',
      gap: '8px',
      marginBottom: '8px'
  });
  const miniBarCountLabel = document.createElement('label');
  miniBarCountLabel.textContent = 'Mini-Bar Count:';
  miniBarCountLabel.htmlFor = 'mini-bar-count-input';
  Object.assign(miniBarCountLabel.style, { flexShrink: '0' });

  const miniBarCountInput = document.createElement('input');
  miniBarCountInput.type = 'number';
  miniBarCountInput.id = 'mini-bar-count-input';
  miniBarCountInput.min = '1';
  miniBarCountInput.max = '50';
  miniBarCountInput.value = miniBarCount;
  Object.assign(miniBarCountInput.style, {
      width: '60px',
      padding: '4px',
      border: '1px solid #555',
      borderRadius: '4px',
      background: 'rgba(255,255,255,0.1)',
      color: '#fff'
  });
  miniBarCountInput.onchange = () => {
      let newValue = parseInt(miniBarCountInput.value, 10);
      if (isNaN(newValue) || newValue < 1) newValue = 1;
      if (newValue > 50) newValue = 50;
      miniBarCount = newValue;
      miniBarCountInput.value = miniBarCount;
      localStorage.setItem(MINI_BAR_COUNT_KEY, miniBarCount.toString());
      refreshAll();
  };
  miniBarCountSettingDiv.append(miniBarCountLabel, miniBarCountInput);
  settingsPanel.appendChild(miniBarCountSettingDiv);

  const resetBtn = document.createElement('button');
  resetBtn.textContent = '🔄 Reset Data';
  Object.assign(resetBtn.style, {
    alignSelf:   'flex-start',
    background:  'rgba(255,255,255,0.1)',
    color:       '#fff',
    border:      'none',
    borderRadius:'6px',
    padding:     '4px 8px',
    cursor:      'pointer'
  });
  resetBtn.onmouseenter = () => resetBtn.style.background = 'rgba(255,255,255,0.2)';
  resetBtn.onmouseleave = () => resetBtn.style.background = 'rgba(255,255,255,0.1)';
  resetBtn.onclick = () => {
    if (confirm('Clear all results and reset profit?')) {
      results     = [];
      totalProfit = 0;
      saveResults();
      saveTotalProfit();
      lastPot     = 0;
      roundActive = true;
      hasTracked  = false;
      alertShownProfit = false;
      alertShownLoss = false;
      localStorage.setItem(ALERT_SHOWN_PROFIT_KEY, 'false');
      localStorage.setItem(ALERT_SHOWN_LOSS_KEY, 'false');
      refreshAll();
    }
  };
  settingsPanel.appendChild(resetBtn);

  const autoHideBtn = document.createElement('button');
  autoHideBtn.textContent = autoHide ? 'Auto-Hide: On' : 'Auto-Hide: Off';
  Object.assign(autoHideBtn.style, {
    alignSelf:   'flex-start',
    background:  'rgba(255,255,255,0.1)',
    color:       '#fff',
    border:      'none',
    borderRadius:'6px',
    padding:     '4px 8px',
    cursor:      'pointer',
    marginTop:   '4px'
  });
  autoHideBtn.onmouseenter = () => autoHideBtn.style.background = 'rgba(255,255,255,0.2)';
  autoHideBtn.onmouseleave = () => autoHideBtn.style.background = 'rgba(255,255,255,0.1)';
  autoHideBtn.onclick = () => {
    autoHide = !autoHide;
    localStorage.setItem(AUTOHIDE_KEY, JSON.stringify(autoHide));
    autoHideBtn.textContent = autoHide ? 'Auto-Hide: On' : 'Auto-Hide: Off';
    refreshAll();
  };
  settingsPanel.appendChild(autoHideBtn);

  const settingsButton = document.createElement('button');
  settingsButton.textContent = '⚙️ Settings';
  Object.assign(settingsButton.style, {
    alignSelf:   'flex-start',
    background:  'rgba(255,255,255,0.1)',
    color:       '#fff',
    border:      'none',
    borderRadius:'6px',
    padding:     '4px 8px',
    cursor:      'pointer',
    marginTop:   '4px'
  });
  settingsButton.onmouseenter = () => settingsButton.style.background = 'rgba(255,255,255,0.2)';
  settingsButton.onmouseleave = () => settingsButton.style.background = 'rgba(255,255,255,0.1)';
  settingsButton.onclick = () => {
      showSettings = true;
      refreshAll();
  };
  panel.appendChild(settingsButton);

  const saveResults   = () => localStorage.setItem(STORAGE, JSON.stringify(results));
  const saveTotalProfit = () => localStorage.setItem(PROFIT_STORAGE, totalProfit.toString());
  const saveCollapsed = () => localStorage.setItem(COLLAPSE_KEY, JSON.stringify(collapsed));

  const makeCircle = (result, bet, index) => {
    const container = document.createElement('span');
    Object.assign(container.style, {
      display:         'inline-block',
      width:           '14px',
      height:          '14px',
      borderRadius:    '50%',
      backgroundColor: result === 'win' ? '#4CAF50' : '#E53935',
      marginRight:     '2px',
      cursor:          'pointer',
      position:        'relative',
    });

    container.title = `${result.toUpperCase()}: $${bet.toLocaleString()}`;

    container.addEventListener('click', (e) => {
        e.stopPropagation();
        // Prevent click action if a single-finger drag or two-finger drag is active
        if (isTwoFingerDragging || panel.style.cursor === 'grabbing') return; // Check grabbing cursor from single-finger drag

        Array.from(container.children).forEach(child => {
            if (child.classList.contains('rr-temp-popup')) {
                container.removeChild(child);
            }
        });

        const tempPopup = document.createElement('div');
        tempPopup.classList.add('rr-temp-popup');
        tempPopup.textContent = `${result.toUpperCase()}: $${bet.toLocaleString()}`;
        Object.assign(tempPopup.style, {
            position: 'absolute',
            background: 'rgba(0,0,0,0.9)',
            border: '1px solid #555',
            color: 'white',
            padding: '4px 8px',
            borderRadius: '4px',
            fontSize: '12px',
            whiteSpace: 'nowrap',
            zIndex: '10000000',
            top: '-28px',
            left: '50%',
            transform: 'translateX(-50%)',
            pointerEvents: 'none',
            opacity: '0',
            transition: 'opacity 0.2s ease-in-out',
        });
        container.appendChild(tempPopup);

        setTimeout(() => tempPopup.style.opacity = '1', 10);
        setTimeout(() => {
            tempPopup.style.opacity = '0';
            setTimeout(() => {
                if (container.contains(tempPopup)) {
                    container.removeChild(tempPopup);
                }
            }, 200);
        }, 1500);
    });

    return container;
  };

  function updateStatus() {
    statusDiv.textContent = collapsed ? '▪' : (roundActive ? '►' : '▸');
  }

  function updatePanelVisibility() {
    if (!autoHide) {
      panel.style.display = 'flex';
      return;
    }
    const onMenu = document.body.innerText.includes('Password');
    panel.style.display = onMenu ? 'flex' : 'none';
  }

  function refreshAll() {
    alertMessageDiv.style.display = 'none';

    let showAlert = false;
    let alertText = '';
    let alertBackgroundColor = '';
    let alertBorderColor = '';

    if (lossLimit > 0 && totalProfit <= -lossLimit) {
        if (!alertShownLoss) {
            alertShownLoss = true;
            localStorage.setItem(ALERT_SHOWN_LOSS_KEY, 'true');
        }
        showAlert = true;
        alertText = `🚨 LOSS LIMIT REACHED! -$${lossLimit.toLocaleString()}`;
        alertBackgroundColor = 'rgba(229, 57, 53, 0.8)';
        alertBorderColor = '#E53935';
    }
    else if (profitTarget > 0 && totalProfit >= profitTarget) {
        if (!alertShownProfit) {
            alertShownProfit = true;
            localStorage.setItem(ALERT_SHOWN_PROFIT_KEY, 'true');
        }
        showAlert = true;
        alertText = `🎯 PROFIT TARGET REACHED! +$${profitTarget.toLocaleString()}`;
        alertBackgroundColor = 'rgba(76, 175, 80, 0.8)';
        alertBorderColor = '#4CAF50';
    }

    if (showAlert) {
        alertMessageDiv.textContent = alertText;
        Object.assign(alertMessageDiv.style, {
            background: alertBackgroundColor,
            borderColor: alertBorderColor,
            display: 'block'
        });
    }

    const sign   = totalProfit >= 0 ? '+' : '–';

    profitMini.textContent = `${sign}${Math.abs(totalProfit).toLocaleString()}`;
    profitMini.style.color = totalProfit >= 0 ? '#4CAF50' : '#E53935';

    profitDiv.textContent  = `💰 Profit: ${sign}$${Math.abs(totalProfit).toLocaleString()}`;
    profitDiv.style.color  = totalProfit >= 0 ? '#4CAF50' : '#E53935';

    const wins = results.filter(r => r.result==='win').length;
    const tot  = results.length;
    winrateDiv.textContent = `🎯 Win Rate: ${tot?((wins/tot)*100).toFixed(1):'0.0'}% (${wins}/${tot})`;

    let w=0,l=0;
    for (const r of results) {
      if (r.result==='win') { if(l) break; w++; }
      else                  { if(w) break; l++; }
    }
    streakDiv.textContent = w?`🔥 Streak: ${w}`: l?`💀 Streak: ${l}`:'⏸️ No streak';

    resultsContainer.innerHTML = '';
    results.slice(0, maxDisplayMatches).forEach((r,i) => {
      const row = document.createElement('div');
      row.append(
        makeCircle(r.result, r.bet, i),
        document.createTextNode(`${i+1}. ${r.result.toUpperCase()} — $${r.bet.toLocaleString()}`)
      );
      resultsContainer.appendChild(row);
    });

    miniBar.innerHTML = '';
    results.slice(0, miniBarCount).forEach((r, i) => miniBar.append(makeCircle(r.result, r.bet, i)));

    if (showSettings) {
        statsGroup.style.display       = 'none';
        settingsButton.style.display   = 'none';
        settingsPanel.style.display    = 'flex';
        miniBar.style.display          = 'none';
        profitMini.style.display       = 'none';
        alertMessageDiv.style.display  = 'none';
    } else if (collapsed) {
        miniBar.style.display          = 'flex';
        profitMini.style.display       = 'block';
        statsGroup.style.display       = 'none';
        settingsButton.style.display   = 'none';
        settingsPanel.style.display    = 'none';
    } else {
        miniBar.style.display          = 'none';
        profitMini.style.display       = 'none';
        statsGroup.style.display       = 'flex';
        settingsButton.style.display   = 'inline-block';
        settingsPanel.style.display    = 'none';
    }

    updateStatus();
    updatePanelVisibility();
  }

  function addResult(type) {
    if (!roundActive) return;

    if (type === 'win') {
        totalProfit += lastPot;
    } else {
        totalProfit -= lastPot;
    }
    saveTotalProfit();

    results.unshift({ result: type, bet: lastPot });
    if (results.length > maxDisplayMatches) {
      results.pop();
    }
    saveResults();
    roundActive = false;
    hasTracked  = true;

    if (profitTarget > 0 && alertShownProfit && totalProfit < profitTarget) {
        alertShownProfit = false;
        localStorage.setItem(ALERT_SHOWN_PROFIT_KEY, 'false');
    }
    if (lossLimit > 0 && alertShownLoss && totalProfit > -lossLimit) {
        alertShownLoss = false;
        localStorage.setItem(ALERT_SHOWN_LOSS_KEY, 'false');
    }

    refreshAll();
  }
  function scanPot() {
    document.querySelectorAll('body *').forEach(el => {
      const txt = el.innerText?.trim();
      if (txt?.includes('POT MONEY:$')) {
        const m = txt.match(/POT MONEY:\$\s*([\d,]+)/);
        if (m) lastPot = Math.floor(parseInt(m[1].replace(/,/g,''),10)/2);
      }
    });
  }
  function scanResult() {
    if (!roundActive) return;
    document.querySelectorAll('body *').forEach(el => {
      const txt = el.innerText?.trim();
      if (txt?.includes('You take your winnings')) addResult('win');
      if (txt?.includes('BANG! You fall down'))    addResult('lose');
    });
  }
  function scanStart() {
    if (hasTracked && document.body.innerText.includes('Waiting:')) {
      roundActive = true;
      hasTracked  = false;
      updateStatus();
    }
  }

  // --- Common drag functionality for the ☰ handle ---
  (function() {
    let mx, my;
    const savePos = () => localStorage.setItem(POS_KEY, JSON.stringify({
      top: panel.style.top, left: panel.style.left
    }));

    function onMove(ev) {
      // Use clientX/Y directly for mouse events
      const clientX = ev.clientX;
      const clientY = ev.clientY;

      const dx = clientX - mx, dy = clientY - my;
      mx = clientX; my = clientY;
      panel.style.top  = panel.offsetTop + dy + 'px';
      panel.style.left = panel.offsetLeft + dx + 'px';
    }

    function onUp() {
      document.removeEventListener('mousemove', onMove);
      document.removeEventListener('mouseup', onUp);
      savePos();
      panel.style.cursor = ''; // Reset cursor
      document.body.style.cursor = ''; // Reset body cursor
    }

    dragHandle.addEventListener('mousedown', e => {
      e.preventDefault();
      mx = e.clientX; my = e.clientY;
      panel.style.cursor = 'grabbing'; // Change cursor while dragging
      document.body.style.cursor = 'grabbing';
      document.addEventListener('mousemove', onMove);
      document.addEventListener('mouseup', onUp);
    });

    // Touch event for the handle remains the same
    dragHandle.addEventListener('touchstart', e => {
      e.preventDefault(); // Prevent scrolling on touch handle drag
      if (e.touches.length === 1) { // Only allow single-finger drag on handle
          mx = e.touches[0].clientX;
          my = e.touches[0].clientY;
          panel.style.cursor = 'grabbing'; // Change cursor while dragging
          document.body.style.cursor = 'grabbing';
          document.addEventListener('touchmove', onMove); // Reusing onMove for touch
          document.addEventListener('touchend', onUp); // Reusing onUp for touch
      }
    });
  })();

  // --- NEW: Two-Finger Drag Implementation for the entire panel ---
  panel.addEventListener('touchstart', e => {
      // Check if two fingers are down AND no other drag is active (like the handle drag)
      if (e.touches.length === 2 && panel.style.cursor !== 'grabbing') {
          e.preventDefault(); // Prevent default two-finger gestures (zoom, scroll)
          isTwoFingerDragging = true;

          // Calculate initial midpoint of touches
          initialTouchMidX = (e.touches[0].clientX + e.touches[1].clientX) / 2;
          initialTouchMidY = (e.touches[0].clientY + e.touches[1].clientY) / 2;

          // Store initial panel position
          initialPanelX = panel.offsetLeft;
          initialPanelY = panel.offsetTop;

          panel.style.cursor = 'grabbing'; // Visual feedback
          document.body.style.cursor = 'grabbing';

          document.addEventListener('touchmove', onTwoFingerMove);
          document.addEventListener('touchend', onTwoFingerEnd);
      }
  });

  function onTwoFingerMove(e) {
      if (!isTwoFingerDragging || e.touches.length !== 2) {
          // If we lose a finger or not in two-finger drag mode, end it
          onTwoFingerEnd();
          return;
      }
      e.preventDefault(); // Prevent default scrolling/zooming during drag

      // Calculate current midpoint of touches
      const currentTouchMidX = (e.touches[0].clientX + e.touches[1].clientX) / 2;
      const currentTouchMidY = (e.touches[0].clientY + e.touches[1].clientY) / 2;

      // Calculate delta from initial midpoint
      const dx = currentTouchMidX - initialTouchMidX;
      const dy = currentTouchMidY - initialTouchMidY;

      // Apply delta to initial panel position
      panel.style.left = (initialPanelX + dx) + 'px';
      panel.style.top  = (initialPanelY + dy) + 'px';
  }

  function onTwoFingerEnd(e) {
      if (!isTwoFingerDragging) return;

      // If touches.length is 0 after touchend, it means all fingers lifted
      // If touches.length is 1, it means one finger lifted, stop two-finger drag
      if (e.touches.length === 0 || e.touches.length === 1) {
          document.removeEventListener('touchmove', onTwoFingerMove);
          document.removeEventListener('touchend', onTwoFingerEnd);
          localStorage.setItem(POS_KEY, JSON.stringify({
              top: panel.style.top, left: panel.style.left
          }));
          isTwoFingerDragging = false;
          panel.style.cursor = ''; // Reset cursor
          document.body.style.cursor = '';
      }
  }


  statusDiv.addEventListener('click', () => {
    // Only toggle collapse if not currently dragging
    if (!isTwoFingerDragging && panel.style.cursor !== 'grabbing') {
        collapsed = !collapsed;
        if (showSettings && collapsed) {
            showSettings = false;
        }
        localStorage.setItem(COLLAPSE_KEY, JSON.stringify(collapsed));
        refreshAll();
    }
  });

  alertMessageDiv.addEventListener('click', () => {
      alertMessageDiv.style.display = 'none';
  });


  refreshAll();
  setInterval(() => {
    updatePanelVisibility();
    scanStart();
    scanPot();
    scanResult();
  }, 500);

})();