/* -----------------------------------------------------------
   AutoBet Panel — dynamic, persistent, progression-aware
   Usage elsewhere: AutoBet.init();
----------------------------------------------------------- */

window.__autobetSpinTriggered = false;

(function () {
  // ----- State -----
  let isTimerRunning = false;
  let countdownInterval = null;
  let remainingTime = 15;
  let autoSpinInterval = null;

  // If your app uses different flags, adjust here:
  const LOSS_FLAG = -1;  // advance to next number
  const WIN_FLAG = 1;  // reset to index 0

  // Storage keys
  const STORE_VALUES_KEY = "autobet_values";   // selector -> "1,2,3"
  const STORE_INDEX_KEY = "autobet_indices";  // selector -> current index

  const MODE_ADVANCE_ON_LOSS = "advance_on_loss";
  const MODE_ADVANCE_ON_WIN = "advance_on_win";
  const MODE_KEEP_PROFIT = "keep_profit";
  const STORE_MODE_KEY = "autobet_mode_v1";

  const runningLossMap = Object.create(null);   // selector -> sum of lost stakes since last win
  const lastBetMap = Object.create(null);   // selector -> last amount wagered

  // Chip map (edit to match your DOM)
  const CHIP_MAP = [
    { value: 10, selector: "#betting_board > div.chipDeck > div.cdChip.orange" },
    { value: 5, selector: "#betting_board > div.chipDeck > div.cdChip.blue" },
    { value: 1, selector: "#betting_board > div.chipDeck > div.cdChip.red" }
  ];

  // Spin button selector (edit to match your DOM)
  const SPIN_BTN_SELECTOR = "#container > div.spinBtn";


  const DATA_VALUES_PREFIX = ''; // e.g. '.ttbbetblock' if needed


  // ---- Presets storage ----
  const STORE_PRESETS_KEY = "autobet_presets_v1";
  const PRESET_STORE_KEY = STORE_PRESETS_KEY;
  const STORE_PROFIT_TARGET_KEY = "autobet_profit_target_v1";



  const STORE_MODE_PER_KEY = "autobet_mode_per_v1";     // selector -> mode
  const STORE_PROFIT_PER_KEY = "autobet_profit_per_v1";   // selector -> profit target

  const perModeMap = loadMap(STORE_MODE_PER_KEY);        // e.g. {"#dozen1": "advance_on_loss"}
  const perProfitMap = loadMap(STORE_PROFIT_PER_KEY);      // e.g. {"#dozen1": "1"}

  // ==== Global/section reset toggles ====
  const STORE_RESET_ALL_KEY = "autobet_reset_all_on_any_v1";
  const STORE_RESET_SECTION_KEY = "autobet_reset_section_map_v1"; // { sectionKey: true/false }

  function getGlobalResetAll() {
    return localStorage.getItem(STORE_RESET_ALL_KEY) === "1";
  }
  function setGlobalResetAll(on) {
    localStorage.setItem(STORE_RESET_ALL_KEY, on ? "1" : "0");
  }

  const resetSectionMap = loadMap(STORE_RESET_SECTION_KEY); // e.g. { dozens: true, rows: false, ... }
  function setSectionReset(sectionKey, on) {
    resetSectionMap[sectionKey] = !!on;
    saveMap(STORE_RESET_SECTION_KEY, resetSectionMap);
  }
  function getSectionReset(sectionKey) {
    return !!resetSectionMap[sectionKey];
  }

  // Map a selector to one of our logical section keys
  function sectionOfSelector(selector) {
    if (!selector) return null;

    // Data-values (splits/straights/quads) take precedence
    const dv = parseDataValuesSelector(selector);
    if (Array.isArray(dv) && dv.length) {
      if (dv.length === 1) return "straights";
      if (dv.length === 2) return "splits";
      if (dv.length === 4) return "quads";
      // non-standard group sizes: no section reset
    }

    if (selector.startsWith("#dozen")) return "dozens";

    if (selector.includes("to18") || selector.includes("9to36") ||
      selector.includes("outsideEven") || selector.includes("outsideOdd") ||
      selector.includes("outsideRed") || selector.includes("outsideBlack")) return "outside";

    if (selector.startsWith("#wlttb_top")) return "double";        // Double streets (5:1)
    if (selector.startsWith("#wlttb_3")) return "streets";       // Streets (11:1)
    if (selector.includes("#row")) return "rows";          // Columns (2:1)

    return null;
  }

  // Get all <input data-selector> in a given section within this panel
  function getSectionInputs(panel, sectionKey) {
    const all = Array.from(panel.querySelectorAll('input[data-selector]'));
    return all.filter(inp => sectionOfSelector(inp.dataset.selector) === sectionKey);
  }

  // Reset just one logical section’s indexes
  function resetSectionIndexes(panel, sectionKey) {
    const inputs = getSectionInputs(panel, sectionKey);
    inputs.forEach(inp => {
      const sel = inp.dataset.selector;
      indexMap[sel] = 0;
    });
    saveMap(STORE_INDEX_KEY, indexMap);
    refreshAllPositionDisplays(panel);
  }

  // Called when a selector experiences a “reset event” (per its mode rule)
  function handleResetEvent(panel, selector) {
    if (getGlobalResetAll()) {
      resetAllIndexes(panel);
      return;
    }
    const sectionKey = sectionOfSelector(selector);
    if (sectionKey && getSectionReset(sectionKey)) {
      resetSectionIndexes(panel, sectionKey);
    }
  }




  function modeFor(selector) {
    // fall back to global if not set yet
    return perModeMap[selector] || getGlobalMode();
  }
  function profitFor(selector) {
    const v = parseFloat(perProfitMap[selector]);
    if (Number.isFinite(v) && v > 0) return v;
    // fall back to global profit target if not set
    return getProfitTarget();
  }




  function getProfitTarget() {
    const v = parseFloat(localStorage.getItem(STORE_PROFIT_TARGET_KEY));
    return Number.isFinite(v) && v > 0 ? v : 1;
  }

  function setProfitTarget(v) {
    const n = parseFloat(v);
    if (Number.isFinite(n) && n > 0) {
      localStorage.setItem(STORE_PROFIT_TARGET_KEY, String(n));
    }
  }

  function getGlobalMode() {
    const v = localStorage.getItem(STORE_MODE_KEY);
    return v || MODE_ADVANCE_ON_LOSS;
  }

  function setGlobalMode(v) {
    localStorage.setItem(STORE_MODE_KEY, v);
  }

  // Returns roulette "pay X:1" odds as an integer (e.g., street => 11)
  function payoutForSelector(selector) {
    // data-values selectors: infer by count
    const dv = parseDataValuesSelector(selector);
    if (dv && dv.length) {
      if (dv.length === 1) return 35; // straight
      if (dv.length === 2) return 17; // split
      if (dv.length === 4) return 8;  // corner (quad)
      // Rare custom groupings are not standard; default to 0 to skip
      return 0;
    }

    // Named regions
    if (selector.startsWith("#wlttb_3")) return 11; // street (3)
    if (selector.startsWith("#wlttb_top")) return 5;  // double street (6)
    if (selector.includes("#row1") || selector.includes("#row2") || selector.includes("#row3")) return 2; // columns
    if (selector.startsWith("#dozen")) return 2;  // dozens

    // Outside: even-money
    if (selector.includes("to18") || selector.includes("9to36") ||
      selector.includes("outsideEven") || selector.includes("outsideOdd") ||
      selector.includes("outsideRed") || selector.includes("outsideBlack")) return 1;

    return 0;
  }


  function loadPresets() {
    try { return JSON.parse(localStorage.getItem(STORE_PRESETS_KEY) || "{}"); }
    catch { return {}; }
  }
  function savePresets(obj) {
    try { localStorage.setItem(STORE_PRESETS_KEY, JSON.stringify(obj)); } catch { }
  }

  // gather current textbox values from the panel (DOM is source of truth)
  function gatherTextboxValues(panel) {
    const data = {};
    const inputs = Array.from(panel.querySelectorAll('input[data-selector]'));
    for (const inp of inputs) {
      const sel = inp.dataset.selector;
      data[sel] = String(inp.value ?? ""); // save exactly what's in the box
    }
    return data;
  }

  function showModal({ title = "", content, onClose }) {
    const overlay = document.createElement("div");
    Object.assign(overlay.style, {
      position: "fixed", inset: 0, background: "rgba(0,0,0,0.45)",
      display: "flex", alignItems: "center", justifyContent: "center",
      zIndex: 10000
    });

    const box = document.createElement("div");
    Object.assign(box.style, {
      width: "min(560px, 92vw)", maxHeight: "80vh", overflowY: "auto",
      background: "#fff", border: "1px solid #ccc", borderRadius: "10px",
      boxShadow: "0 8px 24px rgba(0,0,0,0.30)", padding: "14px"
    });

    const header = document.createElement("div");
    header.textContent = title;
    Object.assign(header.style, { fontWeight: "700", marginBottom: "10px" });

    const close = document.createElement("button");
    close.textContent = "×";
    Object.assign(close.style, {
      float: "right", marginTop: "-6px", marginRight: "-4px",
      background: "#f44336", color: "#fff", border: "none",
      borderRadius: "6px", padding: "2px 8px", cursor: "pointer"
    });
    close.addEventListener("click", () => {
      document.body.removeChild(overlay);
      if (onClose) onClose();
    });

    header.appendChild(close);
    box.appendChild(header);
    box.appendChild(content);
    overlay.appendChild(box);
    document.body.appendChild(overlay);

    return { close: () => { try { document.body.removeChild(overlay); } catch { } } };
  }


  function openSaveDialog(panel) {
    const presets = loadPresets();

    const wrap = document.createElement("div");
    const nameRow = document.createElement("div");
    nameRow.style.marginBottom = "10px";
    const nameLbl = document.createElement("label");
    nameLbl.textContent = "Preset name: ";
    const nameInput = document.createElement("input");
    nameInput.type = "text";
    Object.assign(nameInput.style, { width: "60%" });
    nameRow.appendChild(nameLbl);
    nameRow.appendChild(nameInput);

    const listTitle = document.createElement("div");
    listTitle.textContent = "Existing presets:";
    listTitle.style.margin = "10px 0 6px 0";

    const list = document.createElement("div");
    Object.assign(list.style, { display: "grid", gridTemplateColumns: "1fr auto", gap: "6px" });
    const names = Object.keys(presets).sort();
    if (names.length === 0) {
      const empty = document.createElement("div");
      empty.textContent = "— none saved yet —";
      empty.style.color = "#777";
      list.appendChild(empty);
    } else {
      names.forEach(n => {
        const cellName = document.createElement("div");
        cellName.textContent = n;
        cellName.style.cursor = "pointer";
        cellName.title = "Click to use this name";
        cellName.addEventListener("click", () => { nameInput.value = n; });
        const overwriteBtn = document.createElement("button");
        overwriteBtn.textContent = "Overwrite";
        overwriteBtn.addEventListener("click", () => {
          nameInput.value = n;
        });
        list.appendChild(cellName);
        list.appendChild(overwriteBtn);
      });
    }

    const btnRow = document.createElement("div");
    Object.assign(btnRow.style, { display: "flex", gap: "8px", marginTop: "12px" });
    const saveBtn = document.createElement("button");
    saveBtn.textContent = "Save";
    saveBtn.style.background = "green";
    saveBtn.style.color = "white";
    saveBtn.style.border = "none";
    saveBtn.style.padding = "6px 10px";
    saveBtn.style.borderRadius = "6px";
    saveBtn.style.cursor = "pointer";

    const cancelBtn = document.createElement("button");
    cancelBtn.textContent = "Cancel";

    btnRow.appendChild(cancelBtn);
    btnRow.appendChild(saveBtn);


    wrap.appendChild(nameRow);
    wrap.appendChild(listTitle);
    wrap.appendChild(list);
    wrap.appendChild(btnRow);

    const modal = showModal({ title: "Save Preset", content: wrap });

    cancelBtn.addEventListener("click", modal.close);

    saveBtn.addEventListener("click", () => {
      const name = nameInput.value.trim();
      if (!name) { alert("Please enter a preset name."); return; }
      savePresetByName(panel, name);
      modal.close();
    });
  }

  function openLoadDialog(panel) {
    const wrap = document.createElement("div");

    const list = document.createElement("div");
    Object.assign(list.style, { display: "grid", gridTemplateColumns: "1fr auto auto", gap: "6px" });

    const refresh = () => {
      list.innerHTML = "";
      const presets = loadPresets();
      const names = Object.keys(presets).sort();
      if (names.length === 0) {
        const empty = document.createElement("div");
        empty.textContent = "— no saved presets —";
        empty.style.color = "#777";
        list.appendChild(empty);
        return;
      }
      names.forEach(n => {
        const cellName = document.createElement("div");
        cellName.textContent = n;

        const loadBtn = document.createElement("button");
        loadBtn.textContent = "Load";
        loadBtn.style.cursor = "pointer";

        const delBtn = document.createElement("button");
        delBtn.textContent = "Delete";
        delBtn.style.cursor = "pointer";

        loadBtn.addEventListener("click", () => {
          loadPresetByName(panel, n);
          modal.close();
        });
        delBtn.addEventListener("click", () => {
          const all = loadPresets();
          delete all[n];
          savePresets(all);
          refresh();
        });


        list.appendChild(cellName);
        list.appendChild(delBtn);
        list.appendChild(loadBtn);

      });
    };

    refresh();

    wrap.appendChild(list);

    const modal = showModal({ title: "Load Preset", content: wrap });
  }

  // apply values to DOM + sync valueMap (and reset indexes to 0)
  function applyTextboxValues(panel, values) {
    const inputs = Array.from(panel.querySelectorAll('input[data-selector]'));
    for (const inp of inputs) {
      const sel = inp.dataset.selector;
      if (Object.prototype.hasOwnProperty.call(values, sel)) {
        inp.value = values[sel];
        valueMap[sel] = values[sel];
        indexMap[sel] = 0; // do not persist indexes
        // keep your highlight logic consistent
        inp.dispatchEvent(new Event("input", { bubbles: true }));
        inp.dispatchEvent(new Event("change", { bubbles: true }));
      }
    }
    // persist only values
    saveMap(STORE_VALUES_KEY, valueMap);
  }

  function makeDataValuesSelector(pairStr) {
    // pairStr like "2, 3" -> `[data-values="2, 3"]` or '.ttbbetblock[data-values="2, 3"]'
    const base = `[data-values="${pairStr}"]`;
    return DATA_VALUES_PREFIX ? `${DATA_VALUES_PREFIX}${base}` : base;
  }

  function parseDataValuesSelector(selector) {
    // Accept `[data-values="2, 3"]` or '.something[data-values="2, 3"]'
    const m = selector.match(/data-values\s*=\s*"(.*?)"/i);
    if (!m) return null;
    const nums = (m[1] || '').match(/\d+/g) || [];
    return nums.map(n => parseInt(n, 10)).filter(Number.isFinite);
  }

  // Track which selectors actually placed a bet last cycle
  let lastCyclePlacedSelectors = new Set();
  // Prevent double-advancing for the same roll
  let lastProcessedRollCount = 0;

  /** Return the number set (array<int>) covered by a UI input's selector */
  /** Return the number set (array<int>) covered by a UI input's selector */
  function coverageForSelector(selector) {
    if (!selector) return [];

    // --- NEW: handle [data-values="..."] (e.g., splits)
    // If selector contains data-values, we derive coverage directly from its numbers.
    const dv = parseDataValuesSelector(selector);
    if (Array.isArray(dv) && dv.length) {
      return dv; // e.g. [2, 3] for a split — perfect for win checks
    }

    // --- Existing mappings (dozens / outside / streets / double streets / rows)
    // Dozens
    if (selector.startsWith("#dozen1")) return Array.isArray(DOZEN?.[0]) ? DOZEN[0] : [];
    if (selector.startsWith("#dozen2")) return Array.isArray(DOZEN?.[1]) ? DOZEN[1] : [];
    if (selector.startsWith("#dozen3")) return Array.isArray(DOZEN?.[2]) ? DOZEN[2] : [];

    // Outside bets
    if (selector.includes("to18")) return Array.isArray(LOW) ? LOW : [];   // "#\31 to18"
    if (selector.includes("9to36")) return Array.isArray(HIGH) ? HIGH : [];   // "#\31 9to36"
    if (selector.includes("outsideEven")) return Array.isArray(EVEN) ? EVEN : [];
    if (selector.includes("outsideOdd")) return Array.isArray(ODD) ? ODD : [];
    if (selector.includes("outsideRed")) return Array.isArray(RED) ? RED : [];
    if (selector.includes("outsideBlack")) return Array.isArray(BLACK) ? BLACK : [];

    // Streets: "#wlttb_3 > div:nth-child(n)"
    if (selector.startsWith("#wlttb_3")) {
      const m = selector.match(/nth-child\((\d+)\)/);
      if (m) {
        const idx = parseInt(m[1], 10) - 1;
        return Array.isArray(STREET?.[idx]) ? STREET[idx] : [];
      }
    }

    // Double streets: "#wlttb_top > div:nth-child(n)"
    if (selector.startsWith("#wlttb_top")) {
      const m = selector.match(/nth-child\((\d+)\)/);
      if (m) {
        const idx = parseInt(m[1], 10) - 1;
        return Array.isArray(DOUBLE_STREET?.[idx]) ? DOUBLE_STREET[idx] : [];
      }
    }

    // Columns (rows on your board)
    if (selector.includes("#row1")) return Array.isArray(COLUMN_2TO1?.[0]) ? COLUMN_2TO1[0] : [];
    if (selector.includes("#row2")) return Array.isArray(COLUMN_2TO1?.[1]) ? COLUMN_2TO1[1] : [];
    if (selector.includes("#row3")) return Array.isArray(COLUMN_2TO1?.[2]) ? COLUMN_2TO1[2] : [];

    return [];
  }

  // ---------- Helpers ----------
  function el(tag, props = {}, ...children) {
    const node = document.createElement(tag);

    // Allow an optional "text" prop as a convenience (won't crash if present)
    if (props && typeof props.text !== "undefined") {
      children = [props.text, ...children];
      delete props.text;
    }

    // Apply attributes/styles/listeners
    for (const [k, v] of Object.entries(props || {})) {
      if (k === "style" && v && typeof v === "object") {
        Object.assign(node.style, v);
      } else if (k.startsWith("on") && typeof v === "function") {
        node.addEventListener(k.slice(2), v);
      } else if (k === "dataset" && v && typeof v === "object") {
        for (const [dk, dv] of Object.entries(v)) node.dataset[dk] = dv;
      } else if (k !== "style") {
        // allow id, className, type, value, placeholder, etc.
        node[k] = v;
      }
    }

    // Robust child appender
    const append = (child) => {
      if (child == null || child === false) return; // skip null/undefined/false
      if (Array.isArray(child)) {
        child.forEach(append);
      } else if (child instanceof Node) {
        node.appendChild(child);
      } else if (child instanceof DocumentFragment) {
        node.appendChild(child);
      } else if (typeof child === "string" || typeof child === "number") {
        node.appendChild(document.createTextNode(String(child)));
      } else {
        // Not a Node/string/number/array — ignore but warn for debugging
        // console.warn("el(): skipping non-Node child:", child);
      }
    };

    children.forEach(append);
    return node;
  }

  function loadMap(key) { try { return JSON.parse(localStorage.getItem(key) || "{}"); } catch { return {}; } }
  function saveMap(key, obj) { try { localStorage.setItem(key, JSON.stringify(obj)); } catch { } }

  const valueMap = loadMap(STORE_VALUES_KEY); // e.g. {"#dozen1": "1,2,3"}
  const indexMap = Object.create(null);

  // "1,a,4, 6" -> [1,4,6]; "5" -> [5]; "0" -> [0]; "" -> []
  function parseNumericList(str) {
    if (!str) return [];
    const matches = str.match(/\d+/g);
    if (!matches) return [];
    return matches.map(n => parseInt(n, 10)).filter(Number.isFinite);
  }

  // ---------- Chip placement ----------
  function placeChips(selector, totalChips) {
    let remaining = totalChips;
    for (const chip of CHIP_MAP) {
      const count = Math.floor(remaining / chip.value);
      for (let i = 0; i < count; i++) {
        const chipBtn = document.querySelector(chip.selector);
        const target = document.querySelector(selector);
        if (chipBtn && target) { chipBtn.click(); target.click(); }
      }
      remaining %= chip.value;
    }
  }

  function triggerClick(selector, chips) {
    if (chips > 0) {
      placeChips(selector, chips);
      console.log(`Placed ${chips} chips on ${selector}`);
    }
  }

  // ---------- Progression + persistence ----------
  function currentChipsFor(selector) {
    const seq = parseNumericList(valueMap[selector] ?? "");
    if (!seq.length) return 0;
    const idx = Math.max(0, Math.min(indexMap[selector] ?? 0, seq.length - 1));
    return seq[idx] ?? 0;
  }

function applyWinLossToAll(panel) {
  const rolls = Array.isArray(numbers) ? numbers : [];
  if (!rolls.length) return;

  // Only process once per new roll
  if (rolls.length === lastProcessedRollCount) return;

  const last = parseInt(rolls[rolls.length - 1], 10);
  if (!Number.isFinite(last)) return;

  const inputs = Array.from(panel.querySelectorAll('input[data-selector]'));

  // Work on a staging copy so mid-loop changes don’t fight resets
  const nextIndex = { ...indexMap };

  // Defer resets to the end of the pass
  let globalResetRequested = false;
  const sectionsToReset = new Set();

  for (const inp of inputs) {
    const selector = inp.dataset.selector;
    const mode     = modeFor(selector);

// Only score selectors that actually placed chips last cycle
  if (!lastCyclePlacedSelectors.has(selector)) continue;

  // Extra guard: if last bet amount was 0, skip (non-bet)
  if ((lastBetMap[selector] || 0) <= 0) continue;


    const seq = parseNumericList(valueMap[selector] ?? "");
    if (!seq.length) { nextIndex[selector] = 0; continue; }

    const idx     = Math.max(0, Math.min((indexMap[selector] ?? 0), seq.length - 1));
    const covered = coverageForSelector(selector);
    if (!covered.length) continue;

    const hit = covered.includes(last);

    // Helper: queue a reset effect rather than doing it immediately
    const queueResetIfEnabled = () => {
      if (getGlobalResetAll()) {
        globalResetRequested = true;
        return;
      }
      const sectionKey = sectionOfSelector(selector);
      if (sectionKey && getSectionReset(sectionKey)) {
        sectionsToReset.add(sectionKey);
      }
    };

    if (mode === MODE_ADVANCE_ON_LOSS) {
      // Win -> reset; Loss -> advance
      if (hit) {
        nextIndex[selector] = 0;
        queueResetIfEnabled();
      } else {
        nextIndex[selector] = (idx + 1) % seq.length;
      }
    } else if (mode === MODE_ADVANCE_ON_WIN) {
      // Inverse: Win -> advance; Loss -> reset
      if (hit) {
        nextIndex[selector] = (idx + 1) % seq.length;
      } else {
        nextIndex[selector] = 0;
        queueResetIfEnabled();
      }
    } else if (mode === MODE_KEEP_PROFIT) {
      // Keep-profit: reset on win; losses accumulate (no reset on loss)
      const lastAmt = Math.max(0, lastBetMap[selector] || 0);
      if (hit) {
        nextIndex[selector]       = 0;
        runningLossMap[selector]  = 0;
        queueResetIfEnabled();
      } else {
        runningLossMap[selector]  = (runningLossMap[selector] || 0) + lastAmt;
        nextIndex[selector]       = 0; // display stays at first step
      }
    }
  }

  // Now apply queued resets so they override any increments from this pass
  if (globalResetRequested) {
    // zero everything in panel
    for (const inp of inputs) {
      const sel = inp.dataset.selector;
      nextIndex[sel] = 0;
    }
  } else if (sectionsToReset.size > 0) {
    for (const inp of inputs) {
      const sel = inp.dataset.selector;
      const sec = sectionOfSelector(sel);
      if (sectionsToReset.has(sec)) {
        nextIndex[sel] = 0;
      }
    }
  }

  // Commit staged indexes
  Object.keys(nextIndex).forEach(k => { indexMap[k] = nextIndex[k]; });

  lastProcessedRollCount = rolls.length;
}


    function resetAllIndexes(panel) {
      const inputs = Array.from(panel.querySelectorAll('input[data-selector]'));
      inputs.forEach(inp => {
        const sel = inp.dataset.selector;
        indexMap[sel] = 0;  // reset index
      });
      saveMap(STORE_INDEX_KEY, indexMap);  // persist
      refreshAllPositionDisplays(panel);   // <-- update "(index) amount" tags
      alert("All indexes have been reset to 0.");
    }

    function clearAllInputs(panel) {
      const inputs = Array.from(panel.querySelectorAll('input[data-selector]'));

      inputs.forEach(inp => {
        // Set value
        inp.value = "0";

        // Update maps
        const sel = inp.dataset.selector;
        valueMap[sel] = "0";
        indexMap[sel] = 0;

        // Reset background to white
        inp.style.backgroundColor = "white";

        // Re-run any input-based highlight logic (if you added it in buildNumberInput)
        inp.dispatchEvent(new Event("input", { bubbles: true }));
        // If you also want downstream save/validation to run, you could optionally trigger:
        // inp.dispatchEvent(new Event("change", { bubbles: true }));
      });

      // Persist cleared state
      saveMap(STORE_VALUES_KEY, valueMap);
      saveMap(STORE_INDEX_KEY, indexMap);
    }
    function refreshAllPositionDisplays(panel) {
      const inputs = Array.from(panel.querySelectorAll('input[data-selector]'));
      inputs.forEach(inp => {
        const sel = inp.dataset.selector;
        const seq = parseNumericList(valueMap[sel] ?? inp.value);
        const idx = Math.max(0, Math.min(indexMap[sel] ?? 0, Math.max(0, seq.length - 1)));
        const amount = seq.length ? (seq[idx] ?? 0) : "";

        // vertical layout: span is in the label row (the input's previous sibling)
        // horizontal layout: span may be right after the input
        let span =
          inp.previousElementSibling?.querySelector?.(".pos-display") ||
          inp.nextElementSibling;

        if (span) span.textContent = seq.length ? `(${idx + 1}) ${amount}` : "";
      });
    }

    // ---------- UI builders ----------
    function buildNumberInput(labelText, selector, opts = {}) {
      const input = el("input", {
        type: "text",
        inputMode: "numeric",
        autocomplete: "off",
        spellcheck: false,
        style: {
          width: "140px",
          border: "1px solid #0f0d0dff",
          outline: "none",
          boxShadow: "none",
          fontWeight: "normal"
        }
      });

      input.value = (valueMap[selector] != null)
        ? valueMap[selector]
        : (opts.value != null ? String(opts.value) : "0");

      input.dataset.selector = selector;

      // Span to display (index) amount
      const posDisplay = document.createElement("span");
      posDisplay.className = "pos-display";           // <— add this line
      posDisplay.style.marginLeft = "6px";
      posDisplay.style.fontSize = "12px";
      posDisplay.style.color = "#333";



      function updatePositionDisplay() {
        const seq = parseNumericList(valueMap[selector] ?? input.value);
        const idx = Math.max(0, Math.min(indexMap[selector] ?? 0, seq.length - 1));
        if (seq.length > 0) {
          const amount = seq[idx] ?? 0;
          posDisplay.textContent = `(${idx + 1}) ${amount}`;
        } else {
          posDisplay.textContent = "";
        }
      }

      function updateHighlight() {
        const v = input.value.trim();
        if (v !== "" && v !== "0") {
          input.style.backgroundColor = "#fffdcc";
        } else {
          input.style.backgroundColor = "white";
        }
      }

      function saveFromInput() {
        input.value = input.value.replace(/[^\d,]/g, "").replace(/\s+/g, "");
        valueMap[selector] = input.value;
        const seq = parseNumericList(input.value);
        if (!seq.length) indexMap[selector] = 0;
        else indexMap[selector] = Math.min(indexMap[selector] ?? 0, seq.length - 1);
        saveMap(STORE_VALUES_KEY, valueMap);
        saveMap(STORE_INDEX_KEY, indexMap);
        updateHighlight();
        updatePositionDisplay();
      }

      input.addEventListener("input", updateHighlight);
      input.addEventListener("change", saveFromInput);
      input.addEventListener("blur", saveFromInput);
      input.addEventListener("keyup", e => { if (e.key === "Enter") saveFromInput(); });

      // Initialize states
      updateHighlight();
      updatePositionDisplay();

      const labelEl = el("label", {}, labelText);

      let wrapper;
      if (opts.vertical) {
        // Label and position display on same line, input below
        const labelRow = el("div", {
          style: {
            display: "flex",
            flexDirection: "row",
            alignItems: "center",
            gap: "6px"
          }
        }, [labelEl, posDisplay]);

        wrapper = el("div", {
          style: {
            marginBottom: "6px",
            display: "flex",
            flexDirection: "column",
            alignItems: "flex-start",
            gap: "4px"
          }
        }, [labelRow, input]);

      } else {
        // For horizontal layout (non-vertical), keep inline like before
        const labelInline = el("label", {}, [document.createTextNode(labelText + " "), posDisplay, input]);
        wrapper = el("div", { style: { marginBottom: "6px" } }, [labelInline]);
      }




      // --- Per-input mode controls below this input ---
      const modesRow = el("div", {
        style: {
          display: "flex",
          flexWrap: "wrap",
          gap: "10px",
          alignItems: "center",
          fontSize: "13px"
        }
      });

      // unique-ish base for this input's radios
      const safeSel = selector.replace(/[^a-z0-9]/gi, "_");
      const radioName = `mode_${safeSel}`;

      function mkRadio(label, value) {
        const id = `${radioName}_${value}`;
        const r = el("input", { type: "radio", id, name: radioName, value });
        r.setAttribute("data-mode-for", selector);
        r.checked = (modeFor(selector) === value);
        r.addEventListener("change", () => {
          perModeMap[selector] = value;
          saveMap(STORE_MODE_PER_KEY, perModeMap);
        });
        const l = el("label", { htmlFor: id, style: { marginLeft: "4px", marginRight: "6px" } }, label);
        return el("span", { style: { display: "inline-flex", alignItems: "center" } }, r, l);
      }

      // small input for per-input profit target (shown next to Keep Profit)
      const keepInput = el("input", {
        type: "number",
        min: "0.01",
        step: "0.01",
        style: { width: "58px" },
      });
      keepInput.value = profitFor(selector);
      keepInput.title = "Minimum profit when using Keep Profit";
      keepInput.addEventListener("change", () => {
        perProfitMap[selector] = keepInput.value;
        saveMap(STORE_PROFIT_PER_KEY, perProfitMap);
      });

      // Row content: Loss | Win | Keep Profit [number]
      modesRow.append(
        mkRadio("Loss", MODE_ADVANCE_ON_LOSS),
        mkRadio("Win", MODE_ADVANCE_ON_WIN),
        el("span", { style: { display: "inline-flex", alignItems: "center", gap: "6px" } },
          mkRadio("Keep Profit", MODE_KEEP_PROFIT),
          keepInput
        )
      );



      modesRow.setAttribute("data-mode-for", selector);



      // keep-profit input tagged by selector too
      keepInput.setAttribute("data-keep-profit-for", selector);  // <— add this
      keepInput.value = profitFor(selector);
      keepInput.title = "Minimum profit when using Keep Profit";
      keepInput.addEventListener("change", () => {
        perProfitMap[selector] = keepInput.value;
        saveMap(STORE_PROFIT_PER_KEY, perProfitMap);
      });



      // place row UNDER the input (vertical layout already used for most fields)
      wrapper.appendChild(modesRow);

      return { wrapper, input, label: labelEl, updateHighlight, updatePositionDisplay };
    }


    function buildSection(titleText, sectionKey) {
      const root = el("div", { style: { marginBottom: "10px" } });

      const row = el("div", {
        style: {
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: "8px",
          marginBottom: "6px"
        }
      });

      const titleEl = el("strong", { text: titleText });

      const right = sectionKey ? el("label", {
        style: { display: "inline-flex", alignItems: "center", gap: "6px", fontWeight: 400, fontSize: "12px" }
      }) : null;

      let chk = null;
      if (sectionKey) {
        chk = el("input", { type: "checkbox" });
        // ↓↓↓ NEW: mark this checkbox with the section key so we can update it on load/import
        chk.dataset.sectionReset = sectionKey;
        chk.checked = getSectionReset(sectionKey);
        chk.addEventListener("change", () => setSectionReset(sectionKey, chk.checked));
        right.appendChild(chk);
        right.appendChild(document.createTextNode("Reset all in this section if any bet resets"));
      }

      row.appendChild(titleEl);
      if (right) row.appendChild(right);

      root.appendChild(row);
      return root;
    }



    function buildHelp() {
      return el("div", {
        innerHTML: `<strong>How to use:</strong><br>
      1. Enter sequences like <code>1,2,3</code> (numbers only are stored).<br>
      2. Choose a <em>Progression Mode</em>: Advance on Loss (default), Advance on Win, or Keep Profit (with a minimum profit input box).<br>
      3. "Start Auto-spin" places chips each cycle using the current step (or dynamic amount in Keep-Profit).<br>
      4. "0" in a sequence skips betting that step but still advances (non Keep-Profit).<br>
      5. Values persist; indexes do not (by design).<br>
      6. Use "Clear All" to zero out every field.<br>
      7. The "Start timer for live tables" button is for the live tables feature you set.<br>
      8. You can export your saved bets to share with others.`,
        style: {
          marginBottom: "10px", padding: "8px",
          background: "#f0f8ff", border: "1px solid #ccc",
          borderRadius: "5px", fontSize: "13px"
        }
      });
    }

    function highlightCurrentIndex(input) {
      const sel = input.dataset.selector;
      const seq = (valueMap[sel] || "").split(",");
      const idx = Math.max(0, Math.min(indexMap[sel] ?? 0, seq.length - 1));

      // Build HTML with the current index colored blue
      const colored = seq.map((v, i) => {
        v = v.trim();
        if (i === idx && v !== "") {
          return `<span style="color: blue; font-weight:bold;">${v}</span>`;
        }
        return `<span style="color: black;">${v}</span>`;
      }).join(", ");

      // If there's no overlay yet, create one
      let overlay = input.nextSibling;
      if (!overlay || !overlay.classList || !overlay.classList.contains("highlight-overlay")) {
        overlay = document.createElement("div");
        overlay.className = "highlight-overlay";
        overlay.style.position = "absolute";
        overlay.style.pointerEvents = "none";
        overlay.style.left = input.offsetLeft + "px";
        overlay.style.top = input.offsetTop + "px";
        overlay.style.width = input.offsetWidth + "px";
        overlay.style.height = input.offsetHeight + "px";
        overlay.style.color = "black";
        overlay.style.font = window.getComputedStyle(input).font;
        overlay.style.padding = window.getComputedStyle(input).padding;
        overlay.style.whiteSpace = "nowrap";
        overlay.style.overflow = "hidden";
        overlay.style.zIndex = "1";

        input.parentNode.style.position = "relative";
        input.parentNode.insertBefore(overlay, input);
        input.style.position = "relative";
        input.style.zIndex = "2";
        input.style.color = "transparent"; // hide original text, overlay shows colored text
      }

      overlay.innerHTML = colored;
    }

    function addClearAllButton(panel) {
      // --- New Reset Indexes button ---
      const resetBtn = el("button", {
        id: "resetIndexes",
        text: "Reset Indexes",
        style: {
          width: "100%", marginTop: "5px",
          background: "#fff", color: "#1976d2",
          border: "1px solid #1976d2", padding: "8px",
          borderRadius: "5px", cursor: "pointer"
        }
      });
      resetBtn.addEventListener("click", () => resetAllIndexes(panel));
      panel.appendChild(resetBtn);

      const clearBtn = el("button", {
        id: "clearAllInputs",
        text: "Clear All",
        style: {
          width: "100%",
          marginTop: "5px",
          background: "#fff",
          color: "#b00020",
          border: "1px solid #b00020",
          padding: "8px",
          borderRadius: "5px",
          cursor: "pointer"
        }
      });

      clearBtn.addEventListener("click", () => {
        clearAllInputs(panel);
        clearBtn.textContent = "Cleared";

        setTimeout(() => {
          clearBtn.textContent = "Clear All";
        }, 2000);
      });

      panel.appendChild(clearBtn);
    }

    function makeDraggable(panel) {
      let isDragging = false, offsetX = 0, offsetY = 0;
      panel.addEventListener("mousedown", e => {
        const tag = e.target.tagName;
        if (tag === "INPUT" || tag === "BUTTON" || tag === "SELECT" || tag === "TEXTAREA") return;
        isDragging = true;
        offsetX = e.clientX - panel.offsetLeft;
        offsetY = e.clientY - panel.offsetTop;
        panel.style.cursor = "grabbing";
      });
      document.addEventListener("mousemove", e => {
        if (!isDragging) return;
        panel.style.left = (e.clientX - offsetX) + "px";
        panel.style.top = (e.clientY - offsetY) + "px";
      });
      document.addEventListener("mouseup", () => {
        isDragging = false;
        panel.style.cursor = "move";
      });
    }
    function advancePastZeros(selector) {
      const seq = parseNumericList(valueMap[selector] ?? "");
      if (!seq.length) return; // nothing to do

      let idx = Math.max(0, Math.min(indexMap[selector] ?? 0, seq.length - 1));
      let steps = 0;

      // Move forward until we land on a non-zero step, or we’ve looped all the way around
      while (seq[idx] === 0 && steps < seq.length) {
        idx = (idx + 1) % seq.length;
        steps++;
      }

      indexMap[selector] = idx;
    }

    // ---------- Core actions ----------
function runTimerCycle(panel) {
  // 1) Apply result from previous spin (only affects selectors that actually bet)
  applyWinLossToAll(panel);

  // 2) Fresh set of placed selectors
  lastCyclePlacedSelectors = new Set();

  // Snapshot indexes for display this cycle (pre-advance / pre-placement)
  const displayIndex = { ...indexMap }; // ← this must be a spread, not { .indexMap }

      // 3) Place bets (or skip)
      // 3) Place bets (or skip)
      const inputs = Array.from(panel.querySelectorAll('input[data-selector]'));


      inputs.forEach(inp => {
        const selector = inp.dataset.selector;
        const mode = modeFor(selector);
        const seq = parseNumericList(valueMap[selector] ?? "");
        // Always keep an index entry for display
        if (!seq.length) { indexMap[selector] = 0; return; }

        // Snapshot current index & default step
        let idx = Math.max(0, Math.min(indexMap[selector] ?? 0, seq.length - 1));
        let step = seq[idx] ?? 0;

        // --- Mode 3: Keep Profit of input (use first value only, dynamic raise) ---
        if (mode === MODE_KEEP_PROFIT) {
          // base is the FIRST positive number from the input; if none, skip
          const base = (seq.find(n => n > 0) ?? 0);
          if (base <= 0) { return; }

          const payout = payoutForSelector(selector);
          if (payout <= 0) { return; } // unknown/nonstandard region => skip

          const runningLoss = Math.max(0, runningLossMap[selector] || 0);
          const profitTarget = profitFor(selector); // "at least the entered inputbox" = first value

          // Find smallest integer amt >= base s.t. payout*amt - runningLoss >= profitTarget
          let amt = base;
          while ((payout * amt - runningLoss) < profitTarget) amt += 1;

          step = amt;
          idx = 0; // we conceptually stay on the first step for display
          indexMap[selector] = 0;
        }

        // If step is 0 -> do NOT place a bet this spin; just mark for scoring next spin
 if (step === 0) {
  if (mode !== MODE_KEEP_PROFIT) {
    advancePastZeros(selector);   // skip 0-steps now, so next cycle lands on non-zero
  }
  lastBetMap[selector] = 0;       // explicitly mark as "no bet placed"
  return;
}

        // Non-zero -> place bet
        try { wager = step; } catch (_) { }
        window.wager = step;
        triggerClick(selector, step);
        lastCyclePlacedSelectors.add(selector);
        lastBetMap[selector] = step; // track for loss accrual in keep-profit mode
      });

      // Persist post-cycle index updates (including zero-skips)
      saveMap(STORE_INDEX_KEY, indexMap);

      // --- REFRESH the (index) amount tags based on PRE-ADVANCE snapshot ---
      Array.from(panel.querySelectorAll('input[data-selector]')).forEach(inp => {
        const sel = inp.dataset.selector;
        const seq = parseNumericList(valueMap[sel] ?? inp.value);
        const idx = Math.max(0, Math.min((displayIndex[sel] ?? 0), Math.max(0, seq.length - 1)));
        const amount = seq.length ? (seq[idx] ?? 0) : "";

        // Vertical layout: span is in the label row (the input's previous sibling)
        let span = inp.previousElementSibling?.querySelector?.(".pos-display")
          || inp.previousElementSibling?.querySelector?.("span");

        // Horizontal layout fallback: span may be right after the input
        if (!span) span = inp.nextElementSibling;

        if (span) span.textContent = seq.length ? `(${idx + 1}) ${amount}` : "";
      });


      //numberPadSpin(Math.floor(Math.random() * 37));
      //numberPadSpin(10);
      window.__autobetSpinTriggered = true;
      spin().finally(() => {
        window.__autobetSpinTriggered = false;
      });
    }




    function startTimer(panel, countdownBox, toggleBtn, timerInput) {
      if (isTimerRunning) return;
      isTimerRunning = true;
      remainingTime = parseInt(timerInput.value) || 15;
      countdownBox.textContent = `Countdown: ${remainingTime}s`;

      countdownInterval = setInterval(() => {
        remainingTime--;
        countdownBox.textContent = `Countdown: ${remainingTime}s`;
        if (remainingTime <= 0) {
          runTimerCycle(panel);
          remainingTime = parseInt(timerInput.value) || 15;
          countdownBox.textContent = `Countdown: ${remainingTime}s`;
        }
      }, 1000);

      toggleBtn.textContent = "Pause Timer";
    }

    function stopTimer(toggleBtn) {
      isTimerRunning = false;
      if (countdownInterval) clearInterval(countdownInterval);
      countdownInterval = null;
      if (toggleBtn) toggleBtn.textContent = "Start Timer - For live tables";
    }

    function resetTimer(countdownBox, timerInput) {
      remainingTime = parseInt(timerInput.value) || 15;
      countdownBox.textContent = `Countdown: ${remainingTime}s`;
    }



    function toggleAutoSpin(panel, btn, timerInput) {
      if (autoSpinInterval) {
        clearInterval(autoSpinInterval);
        autoSpinInterval = null;
        btn.textContent = "Start Auto-Spin";
        return;
      }
      const periodMs = Math.max(1, parseInt(timerInput.value) || 15) * 1000;
      autoSpinInterval = setInterval(() => {
        runTimerCycle(panel); // place chips & update progression
        //const spinBtn = document.querySelector(SPIN_BTN_SELECTOR);
        // if (spinBtn) spinBtn.click();
      }, periodMs);
      btn.textContent = "Stop Auto-Spin";
    }




    // ---------- Build panel ----------
    function buildPanel() {

      try { localStorage.removeItem(STORE_INDEX_KEY); } catch (e) { }

      const existing = document.getElementById("autoBetPanel");
      if (existing) return existing;


      const panel = el("div", {
        id: "autoBetPanel",
        style: {
          position: "fixed",
          top: "50px",  // distance of popup from top of browser window
          left: "50px",
          width: "600px",
          maxHeight: "90vh",
          overflowY: "auto",
          background: "white",
          color: "#222",
          border: "2px solid green",
          borderRadius: "10px",
          boxShadow: "0 4px 12px rgba(0,0,0,0.2)",
          zIndex: 9999,
          boxSizing: "border-box",
          padding: "0 15px 15px 15px"
          // note: no top padding here anymore
        }
      });

      //=========================================================================
      //  Start: Header Buttons
      //==========================================================================

      const header = el("div", {
        style: {
          position: "sticky",
          top: 0,
          zIndex: 1,
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: "8px",
          padding: "10px 12px",
          background: "white",
          borderBottom: "1px solid #e5e5e5"
        }
      });

      const titleEl = el("div", { style: { fontWeight: 700, color: "green" } }, "🎰 Auto-Bet Panel");

      const closeBtn = el("button", {
        style: {
          background: "#f44336",
          color: "#fff",
          border: "none",
          borderRadius: "6px",
          padding: "4px 10px",
          cursor: "pointer"
        }
      }, "Close");
      closeBtn.addEventListener("click", () => window.AutoBet?.close?.());

      // ✅ New "Top" button
      const topBtn = el("button", {
        style: {
          background: "#1976d2",
          color: "#fff",
          border: "none",
          borderRadius: "6px",
          padding: "4px 10px",
          cursor: "pointer"
        }
      }, "Top");
      topBtn.addEventListener("click", () => {
        panel.scrollTo({ top: 0, behavior: "smooth" });
      });

      // put title on left, then buttons grouped on right
      const buttonWrap = el("div", { style: { display: "flex", gap: "6px" } }, [topBtn, closeBtn]);

      header.append(titleEl, buttonWrap);




      //=========================================================================
      //  End: Header Buttons
      //==========================================================================



      // Content container: has the padding you wanted
      const content = el("div", {
        style: { padding: "40px 15px 15px 15px", boxSizing: "border-box" }
      });




      // === Master toggle: Reset all on any reset ===
      const masterResetRow = el("div", {
        style: {
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          padding: "8px",
          border: "1px solid #eee",
          borderRadius: "6px",
          margin: "10px 0"
        }
      });

      const masterLbl = el("label", {
        style: { display: "inline-flex", alignItems: "center", gap: "8px", fontWeight: 600 }
      });
      const masterChk = el("input", { type: "checkbox" });
      // ↓↓↓ NEW: make it discoverable during Import/Load
      masterChk.dataset.resetAll = "1";
      masterChk.checked = getGlobalResetAll();
      masterChk.addEventListener("change", () => setGlobalResetAll(masterChk.checked));

      masterLbl.appendChild(masterChk);
      masterLbl.appendChild(document.createTextNode("Reset all on any reset"));
      masterResetRow.appendChild(masterLbl);

      content.appendChild(masterResetRow);





      //=========================================================================
      //  Start: Navigation
      //==========================================================================
      const navTitle = el("div", {
        text: "Quick Navigation",
        style: {
          fontSize: "12px",
          fontWeight: 700,
          color: "#666",
          margin: "8px 0 4px",
          textTransform: "uppercase",
          letterSpacing: "0.06em"
        }
      });






      // wherever you currently do `content.appendChild(navRow)`, replace with:


      // --- Navigation Buttons Row ---
      const navRow = el("div", {
        style: {
          display: "flex",
          gap: "6px",
          marginBottom: "12px",
          overflowX: "auto",
          padding: "6px 0"
        }
      });

      // Mapping: payout -> section id
      const sections = [
        { id: "outside-bets", payout: "1/1" },   // Outside Bets (1:1)
        { id: "dozens", payout: "D" },         // Dozens (2:1)
        { id: "rows", payout: "R" },           // Rows (2:1)
        { id: "double-streets", payout: "5/1" }, // Double Streets (5:1)
        { id: "quads", payout: "8/1" },          // Quads (8:1)
        { id: "streets", payout: "11/1" },       // Streets (11:1)
        { id: "splits", payout: "17/1" },        // Splits (17:1)
        { id: "straights", payout: "35/1" }      // Straights (35:1)
      ];

      // Build buttons
      // inside buildPanel(), where `panel`, `header`, and `content` are in scope
      sections.forEach(sec => {
        const btn = el("button", {
          text: sec.payout,
          style: {
            padding: "6px 10px",
            border: "1px solid #ccc",
            borderRadius: "6px",
            cursor: "pointer",
            background: "#131111ff",
            fontWeight: "bold",
            minWidth: "36px"
          },
          onclick: () => {
            const target = content.querySelector(`#${sec.id}`);
            if (!target) return;

            const scroller = panel;                          // << the scroll container
            const headerHeight = header.offsetHeight || 0;   // sticky header height

            // distance from top of scroller to target, plus current scrollTop
            const targetY =
              target.getBoundingClientRect().top -
              scroller.getBoundingClientRect().top +
              scroller.scrollTop -
              headerHeight - 8; // small breathing room

            scroller.scrollTo({ top: Math.max(0, targetY), behavior: "smooth" });
          }
        });
        navRow.appendChild(btn);
      });


      const navBlock = el("div", { style: { marginBottom: "12px" } }, navTitle, navRow);
      //===========================================================================
      // End: Navigation
      //============================================================================



      // ------------------------------------------------------------------------------------------------------
      // Dozens
      // ------------------------------------------------------------------------------------------------------

      // Dozens
      const secDozens = buildSection("Dozens", "dozens");
      secDozens.id = "dozens";


      secDozens.appendChild(buildNumberInput("1st dozen", "#dozen1", { vertical: true }).wrapper);
      secDozens.appendChild(buildNumberInput("2nd dozen", "#dozen2", { vertical: true }).wrapper);
      secDozens.appendChild(buildNumberInput("3rd dozen", "#dozen3", { vertical: true }).wrapper);

      // ------------------------------------------------------------------------------------------------------
      // Outside Bets
      // ------------------------------------------------------------------------------------------------------

      // Outside Bets
      const secOutside = buildSection("Outside Bets", "outside");
      secOutside.id = "outside-bets";

      secOutside.appendChild(buildNumberInput("1-18", "#\\31 to18", { vertical: true }).wrapper);
      secOutside.appendChild(buildNumberInput("19-36", "#\\31 9to36", { vertical: true }).wrapper);
      secOutside.appendChild(buildNumberInput("EVEN", "#outsideEven", { vertical: true }).wrapper);
      secOutside.appendChild(buildNumberInput("RED", "#outsideRed", { vertical: true }).wrapper);
      secOutside.appendChild(buildNumberInput("BLACK", "#outsideBlack", { vertical: true }).wrapper);
      secOutside.appendChild(buildNumberInput("ODD", "#outsideOdd", { vertical: true }).wrapper);

      // ------------------------------------------------------------------------------------------------------
      // Streets
      // ------------------------------------------------------------------------------------------------------

      // Streets 1–12 with descriptive labels
      const secStreets = buildSection("Streets 1-12", "streets");
      secStreets.id = "streets";
      for (let i = 0; i < 12; i++) {
        const nth = i + 1;

        // Calculate numbers for this street
        const start = i * 3 + 1;            // first number in the row
        const numbers = [start, start + 1, start + 2];

        const labelText = `Street ${numbers.join(", ")}`;

        const { wrapper } = buildNumberInput(
          labelText,
          `#wlttb_3 > div:nth-child(${nth})`,
          { vertical: true }
        );
        secStreets.appendChild(wrapper);
      }




      // ------------------------------------------------------------------------------------------------------
      // Double Sreets
      // ------------------------------------------------------------------------------------------------------

      // --- Double Streets 1–11 ---
      // --- Double Streets 1–11 ---
      const secDouble = buildSection("Double Streets 1-11", "double");
      secDouble.id = "double-streets";

      for (let i = 0; i < 11; i++) {
        const nth = i + 1;

        // Calculate the six numbers covered by this double street (sliding window of 2 streets)
        const startTop = nth * 3 - 2;
        const topRow = [startTop, startTop + 1, startTop + 2];
        const bottomRow = [startTop + 3, startTop + 4, startTop + 5];

        const labelText = `Double Street ${topRow.join(", ")} - ${bottomRow.join(", ")}`;

        // Build vertically so radios + input box all stack correctly
        const { wrapper } = buildNumberInput(
          labelText,
          `#wlttb_top > div:nth-child(${nth})`,
          { vertical: true }
        );

        secDouble.appendChild(wrapper);
      }



      // ------------------------------------------------------------------------------------------------------
      // Quads
      // ------------------------------------------------------------------------------------------------------

      function generateQuads() {
        const quads = [];
        // rows r = 0..10 (top-left row of the 2x2 block)
        // cols c = 1..2  (left or right corner block within the row)
        for (let r = 0; r <= 10; r++) {
          for (let c = 1; c <= 2; c++) {
            const a = r * 3 + c; // top-left number of the 2x2 block
            quads.push([a, a + 1, a + 3, a + 4]); // [a, a+1, a+3, a+4]
          }
        }
        return quads;
      }



      // --- NEW: Quads (Corners)
      const secQuads = buildSection("Quads", "quads");
      secQuads.id = "quads";
      (function addQuads() {
        const wrap = el("div", {
          style: {
            display: "grid",
            gridTemplateColumns: "repeat(2, 1fr)",
            gap: "10px"
          }
        });

        const QUADS = generateQuads(); // [a,b,c,d] arrays

        QUADS.forEach((four) => {
          const labelText = `Quad ${four.join(",")}`;
          const dvStr = four.join(", ");
          const selector = makeDataValuesSelector(dvStr);

          // 🎯 IMPORTANT: ask buildNumberInput to render label above input,
          // and it will include the (index) amount next to the label.
          const { wrapper } = buildNumberInput(labelText, selector, { vertical: true });

          wrap.appendChild(wrapper);
        });

        secQuads.appendChild(wrap);
      })();





      // ------------------------------------------------------------------------------------------------------
      // Splits
      // ------------------------------------------------------------------------------------------------------


      function sortSplitsVertical(splits) {
        return [...splits].sort((a, b) => {
          if (a[0] !== b[0]) {
            return a[0] - b[0]; // Sort by the first number
          }
          return a[1] - b[1];   // If first numbers match, sort by the second
        });
      }

      // --- NEW: Splits (auto from SPLIT in z_variables.js)
      const secSplits = buildSection("Splits", "splits");
      secSplits.id = "splits";

      (function addSplits() {
        const sortedSplits = sortSplitsVertical(SPLIT);
        const wrap = el("div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "6px" } });
        sortedSplits.forEach(pair => {
          const [a, b] = pair;
          const label = `Split ${a},${b}`;
          const dvStr = `${a}, ${b}`;
          const selector = makeDataValuesSelector(dvStr);
          const { wrapper } = buildNumberInput(label, selector);
          wrapper.style.marginBottom = "0";
          wrap.appendChild(wrapper);
        });
        secSplits.appendChild(wrap);
      })();


      // ------------------------------------------------------------------------------------------------------
      // Straights
      // ------------------------------------------------------------------------------------------------------
      // --- NEW: Straights (1–36, then 0 & 00 at bottom)
      const secStraights = buildSection("Straights", "straights");
      secStraights.id = "straights";
      (function addStraights() {
        const wrap = el("div", {
          style: {
            display: "grid",
            gridTemplateColumns: "repeat(3, 1fr)", // 3 columns
            gap: "10px"
          }
        });

        // Create inputs 1-36
        for (let row = 0; row < 12; row++) {
          for (let col = 1; col <= 3; col++) {
            const n = row * 3 + col; // numbers 1..36
            const selector = makeDataValuesSelector(String(n));
            const { wrapper, label, input } = buildNumberInput(`Straight ${n}`, selector);

            // Force vertical layout: label on top, input below
            wrapper.style.display = "flex";
            wrapper.style.flexDirection = "column";
            wrapper.style.alignItems = "flex-start"; // left align; change to center if desired

            wrap.appendChild(wrapper);
          }
        }

        // Bottom row: 0 and 00
        const addZero = (labelTxt, sel) => {
          const { wrapper } = buildNumberInput(labelTxt, makeDataValuesSelector(sel));
          wrapper.style.display = "flex";
          wrapper.style.flexDirection = "column";
          wrapper.style.alignItems = "flex-start";
          wrap.appendChild(wrapper);
        };
        addZero("Straight 0", "0");
        // addZero("Straight 00", "00");
        wrap.appendChild(el("div")); // empty cell to fill the grid row

        secStraights.appendChild(wrap);
      })();



      // ------------------------------------------------------------------------------------------------------
      // Rows
      // ------------------------------------------------------------------------------------------------------



      // Rows
      const secRows = buildSection("Rows", "rows");
      secRows.id = "rows";


      secRows.appendChild(buildNumberInput("Top Row", "#row3", { vertical: true }).wrapper);
      secRows.appendChild(buildNumberInput("Middle Row", "#row2", { vertical: true }).wrapper);
      secRows.appendChild(buildNumberInput("Bottom Row", "#row1", { vertical: true }).wrapper);


      // ------------------------------------------------------------------------------------------------------
      // SAVE LOAD 
      // ------------------------------------------------------------------------------------------------------

      // --- Presets: Save / Load
      const presetRow = el("div", { style: { display: "flex", gap: "8px", marginTop: "8px" } });
      const saveBtn = el("button", {
        text: "Save",
        style: { flex: "1", background: "#1976d2", color: "white", border: "none", padding: "8px", borderRadius: "6px", cursor: "pointer" }
      });
      const loadBtn = el("button", {
        text: "Load",
        style: { flex: "1", background: "#455a64", color: "white", border: "none", padding: "8px", borderRadius: "6px", cursor: "pointer" }
      });

      saveBtn.addEventListener("click", () => openSaveDialog(panel));
      loadBtn.addEventListener("click", () => openLoadDialog(panel));

      presetRow.appendChild(saveBtn);
      presetRow.appendChild(loadBtn);

      ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
      // ----------------------------------------------------------------------------
      // Preset storage keys (bump version so we don't collide with older presets)
      // ----------------------------------------------------------------------------


      // ----------------------------------------------------------------------------
      // SAVE a preset by name (called by your Save dialog)
      // ----------------------------------------------------------------------------
      function savePresetByName(panel, name) {
        if (!name || !name.trim()) return;

        const preset = {
          version: 3,
          values: { ...valueMap },     // textbox values
          indexes: { ...indexMap },     // step indexes
          modes: { ...perModeMap },   // per-input radio mode
          profits: { ...perProfitMap }, // per-input keep-profit numbers
          resetAll: getGlobalResetAll(),
          resetSections: { ...resetSectionMap },
          savedAt: Date.now()
        };

        const all = loadMap(PRESET_STORE_KEY);
        all[name] = preset;
        saveMap(PRESET_STORE_KEY, all);
      }

      // ----------------------------------------------------------------------------
      // LOAD a preset by name (called by your Load dialog)
      // ----------------------------------------------------------------------------
      // Apply a preset object to state + form, same logic your loader uses.
      function applyPresetToPanel(panel, preset) {
        if (!preset) return;

        // 1) Restore base maps
        Object.assign(valueMap, preset.values || {});
        Object.assign(indexMap, preset.indexes || {});
        saveMap(STORE_VALUES_KEY, valueMap);
        saveMap(STORE_INDEX_KEY, indexMap);

        // 2) Restore per-input mode/keep-profit maps
        if (preset.modes) Object.assign(perModeMap, preset.modes);
        if (preset.profits) Object.assign(perProfitMap, preset.profits);
        saveMap(STORE_MODE_PER_KEY, perModeMap);
        saveMap(STORE_PROFIT_PER_KEY, perProfitMap);

        // 3) Restore NEW reset toggles (state + UI)
        if (Object.prototype.hasOwnProperty.call(preset, "resetAll")) {
          setGlobalResetAll(!!preset.resetAll);
        }
        if (preset.resetSections && typeof preset.resetSections === "object") {
          // replace the current map with the incoming one
          for (const k of Object.keys(resetSectionMap)) delete resetSectionMap[k];
          Object.assign(resetSectionMap, preset.resetSections);
          saveMap(STORE_RESET_SECTION_KEY, resetSectionMap);
        }

        // 3a) Reflect toggles to UI checkboxes
        const masterChk = panel.querySelector('input[type="checkbox"][data-reset-all="1"]');
        if (masterChk) masterChk.checked = getGlobalResetAll();

        Array.from(panel.querySelectorAll('input[type="checkbox"][data-section-reset]'))
          .forEach(chk => {
            const key = chk.dataset.sectionReset;
            chk.checked = getSectionReset(key);
          });

        // 4) Push restored values into the UI (existing behavior)
        // 4a) text inputs
        for (const [selector, val] of Object.entries(valueMap)) {
          const inp = Array.from(panel.querySelectorAll('input[data-selector]'))
            .find(n => n.dataset.selector === selector);
          if (inp) inp.value = val;
        }

        // 4b) per-input radios
        for (const [selector, mode] of Object.entries(perModeMap)) {
          const radios = Array.from(panel.querySelectorAll('input[type="radio"][data-mode-for]'))
            .filter(r => r.dataset.modeFor === selector);
          let matched = false;
          radios.forEach((r) => {
            const isMatch = r.value === mode;
            r.checked = isMatch;
            if (isMatch) matched = true;
          });
          if (!matched && radios.length) radios[0].checked = true;
        }

        // 4c) keep-profit inputs
        for (const [selector, val] of Object.entries(perProfitMap)) {
          const kp = Array.from(panel.querySelectorAll('input[data-keep-profit-for]'))
            .find(n => n.dataset.keepProfitFor === selector);
          if (kp && val != null) kp.value = val;
        }

        // 5) Derived displays
        if (typeof refreshDisplays === "function") refreshDisplays(panel);
      }



      function loadPresetByName(panel, name) {
        const all = loadMap(PRESET_STORE_KEY);
        const preset = all[name];
        if (!preset) return;
        applyPresetToPanel(panel, preset);
      }

      window.savePresetByName = savePresetByName;
      window.loadPresetByName = loadPresetByName;

      // --- helpers: take/apply a snapshot of just the form controls in this panel ---
      function takeFormSnapshot(root) {
        const values = {};
        const modes = {};
        const profits = {};

        // Any input with data-selector (text/number/checkbox)
        root.querySelectorAll('input[data-selector]').forEach(inp => {
          const key = inp.dataset.selector;
          if (!key) return;
          if (inp.type === 'checkbox') {
            values[key] = !!inp.checked;
          } else if (inp.type === 'number') {
            const n = inp.value === '' ? null : Number(inp.value);
            values[key] = Number.isFinite(n) ? n : inp.value;
          } else {
            values[key] = inp.value;
          }
        });

        // Per-input mode radios (like 3 options per field)
        root.querySelectorAll('input[type="radio"][data-mode-for]').forEach(r => {
          if (!r.checked) return;
          modes[r.dataset.modeFor] = r.value;
        });

        // Per-input "keep profit" numbers
        root.querySelectorAll('input[data-keep-profit-for]').forEach(inp => {
          const key = inp.dataset.keepProfitFor;
          const n = inp.value === '' ? null : Number(inp.value);
          // store only if set
          if (inp.value !== '') profits[key] = Number.isFinite(n) ? n : inp.value;
        });

        return {
          kind: "AutoBetFormSnapshot",
          version: 1,
          exportedAt: Date.now(),
          values,
          modes,
          profits,
        };
      }

      function applyFormSnapshot(root, snap) {
        if (!snap || typeof snap !== 'object') throw new Error("Bad snapshot");
        const values = snap.values || {};
        const modes = snap.modes || {};
        const profits = snap.profits || {};

        // 1) Write values into inputs (and fire events so your code reacts)
        root.querySelectorAll('input[data-selector]').forEach(inp => {
          const key = inp.dataset.selector;
          if (!(key in values)) return;
          if (inp.type === 'checkbox') {
            const newVal = !!values[key];
            if (inp.checked !== newVal) {
              inp.checked = newVal;
              inp.dispatchEvent(new Event('change', { bubbles: true }));
            }
          } else {
            const newVal = values[key] ?? '';
            if (inp.value !== String(newVal)) {
              inp.value = newVal;
              // trigger both input & change to catch whichever you listen for
              inp.dispatchEvent(new Event('input', { bubbles: true }));
              inp.dispatchEvent(new Event('change', { bubbles: true }));
            }
          }
        });

        // 2) Set per-input mode radios
        Object.entries(modes).forEach(([selector, modeVal]) => {
          const group = Array.from(root.querySelectorAll(`input[type="radio"][data-mode-for="${selector}"]`));
          const target = group.find(r => r.value === String(modeVal)) || group[0];
          if (target && !target.checked) {
            target.checked = true;
            target.dispatchEvent(new Event('change', { bubbles: true }));
          }
        });

        // 3) Set keep-profit fields
        Object.entries(profits).forEach(([selector, v]) => {
          const inp = root.querySelector(`input[data-keep-profit-for="${selector}"]`);
          if (!inp) return;
          const val = v ?? '';
          if (inp.value !== String(val)) {
            inp.value = val;
            inp.dispatchEvent(new Event('input', { bubbles: true }));
            inp.dispatchEvent(new Event('change', { bubbles: true }));
          }
        });

        // 4) Optional: refresh any derived UI if you have a helper
        if (typeof refreshAllPositionDisplays === 'function') {
          refreshAllPositionDisplays(root);
        }

        // 5) Optional: keep in-memory maps in sync (NO saving to presets/localStorage)
        if (typeof valueMap === 'object') Object.assign(valueMap, values);
        if (typeof perModeMap === 'object') Object.assign(perModeMap, modes);
        if (typeof perProfitMap === 'object') Object.assign(perProfitMap, profits);
      }

      // ------- Buttons: Export (download) & Load (from file) -------

      // === Snapshot the ENTIRE form ===
      // Captures: inputs with data-selector, per-field mode radios, per-field keep-profit inputs
      function takeFormSnapshot(root) {
        const values = {};
        const modes = {};
        const profits = {};

        // Text/number/checkbox (and <select>) controls that drive betting, tagged with data-selector
        root.querySelectorAll('input[data-selector], select[data-selector], textarea[data-selector]')
          .forEach(el => {
            const key = el.dataset.selector;
            if (!key) return;
            if (el.type === 'checkbox') {
              values[key] = !!el.checked;
            } else {
              values[key] = String(el.value ?? '');
            }
          });

        // Per-input radio “mode” selections (Loss / Win / Keep Profit)
        root.querySelectorAll('input[type="radio"][data-mode-for]').forEach(r => {
          if (r.checked) modes[r.dataset.modeFor] = r.value;
        });

        // Per-input keep-profit number fields
        root.querySelectorAll('input[data-keep-profit-for]').forEach(inp => {
          const k = inp.dataset.keepProfitFor;
          // store only if present; keep as string so your code can parse it
          if (inp.value !== '') profits[k] = String(inp.value);
        });

        return {
          kind: "AutoBetFormSnapshot",
          version: 1,
          exportedAt: Date.now(),
          values,
          modes,
          profits
        };
      }


      // --- Export (same data as "Save", but downloaded) ---
      const exportBtn = el("button", {
        text: "Export",
        style: {
          flex: "1",
          background: "#6a1b9a",
          color: "white",
          border: "none",
          padding: "8px",
          borderRadius: "6px",
          cursor: "pointer"
        },
        onclick: () => {
          // Make sure values reflect the *current* inputs before snapshot
          if (typeof gatherTextboxValues === "function") {
            Object.assign(valueMap, gatherTextboxValues(panel)); // sync from DOM
            saveMap(STORE_VALUES_KEY, valueMap);
          }

          const preset = {
            version: 3,
            values: { ...valueMap },     // textbox values
            indexes: { ...indexMap },     // step indexes
            modes: { ...perModeMap },   // per-input radio mode
            profits: { ...perProfitMap }, // per-input keep-profit numbers
            resetAll: getGlobalResetAll(),
            resetSections: { ...resetSectionMap },
            savedAt: Date.now()
          };


          const defName = `Preset_${new Date().toISOString().replace(/[:T]/g, '-').slice(0, 19)}`;
          const blob = new Blob([JSON.stringify(preset, null, 2)], { type: "application/json" });
          const url = URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.href = url;
          a.download = `${defName}.json`;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          URL.revokeObjectURL(url);
        }
      });

      // --- Import (same effect as your "Load Presets", but from a file) ---
      const importBtn = el("button", {
        text: "Import",
        style: {
          flex: "1",
          background: "#ff9800",
          color: "white",
          border: "none",
          padding: "8px",
          borderRadius: "6px",
          cursor: "pointer"
        },
        onclick: () => {
          const input = document.createElement("input");
          input.type = "file";
          input.accept = ".json,application/json";

          input.addEventListener("change", e => {
            const file = e.target.files && e.target.files[0];
            if (!file) return;

            const reader = new FileReader();
            reader.onload = ev => {
              try {
                const data = JSON.parse(ev.target.result);

                // Accept either a single snapshot {values,...} or a bucket { name: snapshot, ... }.
                let preset = null;
                if (data && typeof data === "object" && data.values) {
                  preset = data;
                } else if (data && typeof data === "object") {
                  const names = Object.keys(data).filter(k => data[k] && data[k].values);
                  if (!names.length) throw new Error("No preset found in file.");
                  // Pick the most recent by savedAt if present; else first
                  names.sort((a, b) => (data[b].savedAt || 0) - (data[a].savedAt || 0));
                  preset = data[names[0]];
                } else {
                  throw new Error("Unrecognized file format.");
                }

                applyPresetToPanel(panel, preset); // <-- reuse your Load logic

              } catch (err) {
                console.error(err);
                alert("❌ Import failed: " + err.message);
              }
            };
            reader.readAsText(file);
          });

          input.click();
        }
      });

      // Place these next to your Save/Load row
      presetRow.appendChild(exportBtn);
      presetRow.appendChild(importBtn);





      // ------------------------------------------------------------------------------------------------------
      // Radio Button index options
      // ------------------------------------------------------------------------------------------------------
      // --- Progression Mode Radios ---
      const modeWrap = el("div", { style: { margin: "10px 0 12px 0", padding: "8px", border: "1px solid #eee", borderRadius: "6px" } });

      const mkRadio = (id, label, value) => {
        const r = el("input", { type: "radio", name: "autobet_mode", id, value });
        const l = el("label", { htmlFor: id, style: { marginLeft: "6px", marginRight: "14px", fontWeight: 500 } }, label);
        const box = el("span", { style: { marginRight: "12px" } }, r, l);
        r.addEventListener("change", () => setGlobalMode(value));
        return { box, r };
      };

      const r1 = mkRadio("modeLoss", "Advance on Loss", MODE_ADVANCE_ON_LOSS);
      const r2 = mkRadio("modeWin", "Advance on Win", MODE_ADVANCE_ON_WIN);
      // Create a wrapper span for Keep Profit with an input box
      const keepProfitInput = el("input", {
        type: "number",
        min: "0.01",
        step: "0.01",
        value: getProfitTarget(),
        style: { width: "50px", marginLeft: "6px" }
      });
      keepProfitInput.addEventListener("change", () => setProfitTarget(keepProfitInput.value));

      const keepProfitLabel = el("label", { htmlFor: "modeKeep", style: { marginLeft: "6px", marginRight: "14px", fontWeight: 500 } }, "Keep Profit");
      const keepProfitRadio = el("input", { type: "radio", name: "autobet_mode", id: "modeKeep", value: MODE_KEEP_PROFIT });
      keepProfitRadio.addEventListener("change", () => setGlobalMode(MODE_KEEP_PROFIT));

      // Wrap label + input together
      const keepBox = el("span", { style: { marginRight: "12px" } }, keepProfitRadio, keepProfitLabel, keepProfitInput);


      modeWrap.append(el("div", { style: { marginBottom: "6px", fontWeight: 600 } }, "Progression Mode"));
      modeWrap.append(r1.box, r2.box, keepBox);


      // initialize selection
      const modeNow = getGlobalMode();
      ({ [MODE_ADVANCE_ON_LOSS]: r1.r, [MODE_ADVANCE_ON_WIN]: r2.r, [MODE_KEEP_PROFIT]: keepProfitRadio }[modeNow] || r1.r).checked = true;

      modeWrap.style.display = "none"; // HIDE PANEL


      //==========================================================================================================
      // START: Spin Buttons Section
      //==========================================================================================================
      // --- Controls block (goes under Save/Load and ABOVE nav buttons) ---
      function buildControlsBlock(panel) {
        const wrap = el("div", {
          id: "autoControls",
          style: {
            display: "grid",
            gap: "8px",
            margin: "10px 0 12px 0",
            padding: "10px",
            border: "1px solid #eee",
            borderRadius: "8px",
            background: "#fafafa"
          }
        });



        // Utility buttons row: Reset Indexes, Clear All, Start/Stop Auto-Spin
        const utilityRow = el("div", { style: { display: "grid", gap: "8px" } });

        const resetIdxBtn = el("button", {
          id: "resetIndexes",
          text: "Reset Indexes",
          style: {
            width: "100%",
            background: "#fff",
            color: "#1976d2",
            border: "1px solid #1976d2",
            padding: "8px",
            borderRadius: "6px",
            cursor: "pointer"
          }
        });
        resetIdxBtn.addEventListener("click", () => resetAllIndexes(panel));

        const clearBtn = el("button", {
          id: "clearAllInputs",
          text: "Clear All",
          style: {
            width: "100%",
            background: "#fff",
            color: "#b00020",
            border: "1px solid #b00020",
            padding: "8px",
            borderRadius: "6px",
            cursor: "pointer"
          }
        });
        clearBtn.addEventListener("click", () => {
          clearAllInputs(panel);
          clearBtn.textContent = "Cleared";
          setTimeout(() => (clearBtn.textContent = "Clear All"), 2000);
        });

        const autoSpinBtn = el("button", {
          id: "autoSpinBtn",
          text: "Start Auto-Spin",
          style: {
            width: "100%",
            background: "darkgreen",
            color: "white",
            border: "none",
            padding: "8px",
            borderRadius: "6px",
            cursor: "pointer"
          }
        });
        const info = el("div", {
          text: "Please wait 15 secs for spin",
          style: { textAlign: "center", color: "#333", fontSize: "12px" }
        });

        utilityRow.append(resetIdxBtn, clearBtn);
        wrap.appendChild(utilityRow);

        // Wire up the three interactive controls (reuse your existing functions)


        autoSpinBtn.addEventListener("click", () => toggleAutoSpin(panel, autoSpinBtn, timerInput));

        return wrap;
      }

      // Insert controls block right after Save/Load and BEFORE navRow:
      const controlsBlock = buildControlsBlock(panel);

      //==========================================================================================================
      // END: Spin Buttons Section
      //==========================================================================================================
      //==========================================================================================================
      // START: AUTO-SPIN Button
      //==========================================================================================================
      // === Mount the existing "Auto Spin" button under Save/Load ===
      const autoSpinMount = el("div", {
        style: {
          margin: "8px 0 10px 0",
          display: "flex",
          gap: "8px"
        }
      });

      // Try to use the already-created shared button
      // get the real shared button or create it if needed
      let autoBtn = window.button_autoButton;
      if (!(autoBtn instanceof HTMLElement) && typeof window.toggleAutoPlayButton === "function") {
        // also sets window.button_autoButton internally
        autoBtn = window.toggleAutoPlayButton(true);
      }

      const autoBtnOrigParent = autoBtn?.parentNode || null;
      const autoBtnOrigNext = autoBtn?.nextSibling || null;

      // popup-only layout overrides (won’t affect when it’s back on the page)
      const popupCSS = document.createElement("style");
      popupCSS.textContent = `
  /* only affects the button when it's inside the popup */
  #autoBetPanel #countdownBtn {
    position: static !important;
    margin: 0 !important;

    /* make it match the Start Auto-Spin button's full width */
    width: 100% !important;
    height: auto !important;
    display: block !important;
    box-sizing: border-box;

    /* optional: similar look/feel */
    padding: 8px !important;
    border-radius: 6px !important;
    border: none !important;
  }
`;
      panel.appendChild(popupCSS);

      // move the real node into the popup
      if (autoBtn) autoSpinMount.appendChild(autoBtn);


      function restoreAutoSpinButton() {
        if (autoBtn && autoBtnOrigParent) {
          if (autoBtnOrigNext && autoBtnOrigNext.parentNode === autoBtnOrigParent) {
            autoBtnOrigParent.insertBefore(autoBtn, autoBtnOrigNext);
          } else {
            autoBtnOrigParent.appendChild(autoBtn);
          }
        }
      }
      const originalClose = window.AutoBet?.close;
      closeBtn.addEventListener("click", () => {
        restoreAutoSpinButton();
        if (typeof originalClose === "function") originalClose();
      });

      //==========================================================================================================
      // END:  AUTO-SPIN Button
      //==========================================================================================================

      // ------------------------------------------------------------------------------------------------------
      // Add input to panel
      // ------------------------------------------------------------------------------------------------------

      //content.appendChild(navRow);
      content.appendChild(modeWrap);
      content.appendChild(buildHelp());
      content.appendChild(presetRow); // save load cache

      content.appendChild(controlsBlock);
      content.appendChild(autoSpinMount);
      content.appendChild(navBlock);
      content.appendChild(secOutside); // Outside Bets
      content.appendChild(secDozens); // Dozens
      content.appendChild(secRows); // Rows
      content.appendChild(secDouble); // Double Streets
      content.appendChild(secStreets); // Streets
      content.appendChild(secQuads); // Quads
      content.appendChild(secSplits); // Splits
      content.appendChild(secStraights); // Straights



      panel.appendChild(header);
      panel.appendChild(content);





      // Draggable
      makeDraggable(panel);

      document.body.appendChild(panel);
      return panel;
    }

    function ensureOpenButton() {
      if (document.getElementById("openAutoBet")) return;
      const btn = el("button", {
        id: "openAutoBet",
        text: "Auto-Bet Panel",
        style: {
          position: "fixed", bottom: "20px", right: "20px", zIndex: "9999",
          padding: "10px 15px", background: "green", color: "white",
          fontWeight: "bold", border: "none", borderRadius: "8px",
          cursor: "pointer", boxShadow: "0 2px 6px rgba(0,0,0,0.3)"
        }
      });
      btn.addEventListener("click", () => buildPanel());
      document.body.appendChild(btn);
    }

    function initIndexes(panel) {
      const inputs = Array.from(panel.querySelectorAll('input[data-selector]'));
      for (const inp of inputs) {
        const sel = inp.dataset.selector;
        if (!(sel in indexMap)) indexMap[sel] = 0;
      }
    }

    // 2) Extract the chip placement into a reusable helper
    function placeChipsForCycle(panel) {
      // Fresh set of placed selectors
      lastCyclePlacedSelectors = new Set();

      const inputs = Array.from(panel.querySelectorAll('input[data-selector]'));
      inputs.forEach(inp => {
        const selector = inp.dataset.selector;
        const mode = modeFor(selector);
        const seq = parseNumericList(valueMap[selector] ?? "");
        if (!seq.length) { indexMap[selector] = 0; return; }

        let idx = Math.max(0, Math.min(indexMap[selector] ?? 0, seq.length - 1));
        let step = seq[idx] ?? 0;

        // Keep Profit mode logic
        if (mode === MODE_KEEP_PROFIT) {
          const base = (seq.find(n => n > 0) ?? 0);
          if (base <= 0) return;
          const payout = payoutForSelector(selector);
          if (payout <= 0) return;
          const runningLoss = Math.max(0, runningLossMap[selector] || 0);
          const profitTarget = profitFor(selector);
          let amt = base;
          while ((payout * amt - runningLoss) < profitTarget) amt += 1;
          step = amt;
          idx = 0;
          indexMap[selector] = 0;
        }

        // If step is zero, we “ghost place” (for scoring next spin) but don’t click
if (step === 0) {
  if (mode !== MODE_KEEP_PROFIT) {
    advancePastZeros(selector);   // skip 0-steps now, so next cycle lands on non-zero
  }
  lastBetMap[selector] = 0;       // explicitly mark as "no bet placed"
  return;
}

        // Non-zero — actually place chips
        try { wager = step; } catch (_) { }
        window.wager = step;
        triggerClick(selector, step);
        lastCyclePlacedSelectors.add(selector);
        lastBetMap[selector] = step;
      });

      // Persist index map after this placement phase
      saveMap(STORE_INDEX_KEY, indexMap);
    }


    function ensurePanel() {
      let p = document.getElementById("autoBetPanel");
      if (!p && typeof buildPanel === "function") p = buildPanel();
      return p;
    }

    // Public: call this AFTER you’ve appended a number to `numbers[]`
    function onSpinResolvedPublic() {
      const p = getPanel();            // was: ensurePanel()
      if (!p) return;
      applyWinLossToAll(p);
      refreshAllPositionDisplays(p);
    }
    function advanceThenPlacePublic() {
      const p = getPanel();            // was: document.getElementById(...) || buildPanel()
      if (!p) return;
      applyWinLossToAll(p);
      if (typeof placeChipsForCycle === "function") placeChipsForCycle(p);
      refreshAllPositionDisplays(p);
    }
    // add once
    function getPanel() {
      return document.getElementById("autoBetPanel");
    }


    // ---------- Public API ----------
    window.AutoBet = {
      init() { ensureOpenButton(); },
      runTimerCycle() { const p = document.getElementById("autoBetPanel"); if (p) runTimerCycle(p); },
      start() {
        let p = document.getElementById("autoBetPanel");
        if (!p) p = buildPanel();
        initIndexes(p);
        const c = p.querySelector("#autoCountdown");
        const t = p.querySelector("#toggleAutoBet");
        const i = p.querySelector("#timerIntervalInput");
        startTimer(p, c, t, i);
      },
      stop() { const t = document.querySelector("#toggleAutoBet"); stopTimer(t); },
      open() { buildPanel(); },
      close() {
        // Stop timer if running
        if (countdownInterval) clearInterval(countdownInterval);
        countdownInterval = null;
        isTimerRunning = false;

        // Stop auto-spin if running
        if (autoSpinInterval) clearInterval(autoSpinInterval);
        autoSpinInterval = null;

        // Reset toggle button text if panel is open
        const t = document.querySelector("#toggleAutoBet");
        if (t) t.textContent = "Start Timer for live tables";
        const a = document.querySelector("#autoSpinBtn");
        if (a) a.textContent = "Start Auto-Spin";

        // Remove panel
        const p = document.getElementById("autoBetPanel");
        if (p) p.remove();
        window.__autobetSpinTriggered = false;
      },
      isRunning() { return isTimerRunning; },
      placeChipsOnly() {
        const p = getPanel();            // was: ensurePanel()
        if (!p) return;
        if (typeof placeChipsForCycle === "function") placeChipsForCycle(p);
      },
      advanceThenPlace: advanceThenPlacePublic,
  };
})();