/* Buttons + smooth open/close (JS-only, no <style> tags) */

/* --- helper: create buttons and content with inline-transition animation --- */

const buttonState = {
  'buttonBar-button-1': false,
  'buttonBar-button-2': false,
  'buttonBar-button-3': false,
  'buttonBar-button-4': false,
  'buttonBar-button-5': false,
  'buttonBar-button-6': false,
  'buttonBar-button-7': false,
  'buttonBar-button-9': false,
  'buttonBar-button-10': false,
  'buttonBar-button-11': false,
  'buttonBar-button-12': false,
  'buttonBar-button-13': false,
  'buttonBar-button-14': false,
  'buttonBar-button-15': false,
  'buttonBar-button-19': false,
  'buttonBar-button-20': false,
  'buttonBar-button-21': false,
  'buttonBar-button-22': false,
};

function addButtonsToButtonBar(){
  makeButtonForButtonBar("1", "Frequency", frequencyBuild);
  makeButtonForButtonBar("2", "Cold", coldBuild);
  makeButtonForButtonBar("3", "Hover", createHoverNumbers);
  makeButtonForButtonBar("4", "Once", onceBuild);
  makeButtonForButtonBar("5", "Streets", buildTable);
  makeButtonForButtonBar("6", "Missed", allMissed);
  makeButtonForButtonBar("7", "Pattern", getPattern);
  makeButtonForButtonBar("9", "Record", createMissesTable);
  makeButtonForButtonBar("10", "Next Bet", nextBet);
  makeButtonForButtonBar("11", "Neighbors", neighborBuild);

  if (typeof dozenOrRow !== 'undefined' && dozenOrRow == 'dozen') makeButtonForButtonBar("12", "Bouncy", bounce);
  if (typeof dozenOrRow !== 'undefined' && dozenOrRow == 'row') makeButtonForButtonBar("12", "Bouncy", bounce_bounceRow);

  makeButtonForButtonBar("13", "Combo", combo);
  makeButtonForButtonBar("15", "Edge", coldBuild_edge_3);

  makeButtonForButtonBar("19", "Pop-ups", buildStatsPage);
  makeButtonForButtonBar("20", "Simulations", simulation_options);
  makeButtonForButtonBar("21", "Profit Chart", createProfitChartWidget);
  makeButtonForButtonBar("22", "Bet Payout", getAllBets);
}

function makeButtonForButtonBar(id, title, functionCall) {
  const button = document.createElement('button');
  button.id = `buttonBar-button-${id}`;
  button.textContent = title;
  button.style.padding = '5px';
  button.style.marginRight = '5px';
  button.onclick = buttonBarContents.bind(null, id, functionCall);
  const bar = document.getElementById('button-bar');
  if (!bar) {
    console.warn('button-bar element not found in DOM');
    return;
  }
  bar.appendChild(button);
}

function toggleButton(buttonId) {
  const button = document.getElementById(buttonId);
  if (!button) return;
  buttonState[buttonId] = !buttonState[buttonId];
  button.style.backgroundColor = buttonState[buttonId] ? 'lightgreen' : '';
}

/* ---------- persistent observers to handle post-open growth ---------- */

function attachGrowthObservers(el) {
  // If already attached, skip
  if (el.__growthObserversAttached) return;
  el.__growthObserversAttached = true;

  // ResizeObserver: when contents change size, ensure the panel grows
  try {
    const ro = new ResizeObserver(() => {
      if (el.style.display !== 'none') {
        // Keep height 'auto' so it can grow naturally after open
        el.style.height = 'auto';
        // Touch layout to ensure reflow
        void el.offsetHeight;
      }
    });
    ro.observe(el);
    el.__ro = ro;
  } catch (_) {}

  // MutationObserver: if DOM nodes are added (like the Sleeper chart),
  // nudge layout immediately even before resize fires in some browsers.
  try {
    const mo = new MutationObserver(() => {
      if (el.style.display !== 'none') {
        el.style.height = 'auto';
        void el.offsetHeight;
      }
    });
    mo.observe(el, { childList: true, subtree: true });
    el.__mo = mo;
  } catch (_) {}
}

function detachGrowthObservers(el) {
  try { el.__ro?.disconnect?.(); } catch(_) {}
  try { el.__mo?.disconnect?.(); } catch(_) {}
  el.__ro = null;
  el.__mo = null;
  el.__growthObserversAttached = false;
}

/* ---------- animation helpers (inline styles only) ---------- */

function animateOpen(el) {
  if (!el) return;

  setTransitioning(el, true);

  // Make it visible & set start state
  el.style.display = el._displayBefore || 'block';
  el.style.overflow = 'hidden';
  el.style.boxSizing = 'border-box';
  el.style.opacity = '0';
  el.style.height = '0px';
  el.style.transition = 'height 0.36s ease, opacity 0.28s ease';

  // Force reflow
  el.offsetHeight;

  const setHeightToScroll = () => { el.style.height = el.scrollHeight + 'px'; };

  // Track size DURING opening (growing content while opening)
  let roDuring;
  try {
    roDuring = new ResizeObserver(() => {
      if (el.style.transition) setHeightToScroll();
    });
    roDuring.observe(el);
  } catch (_) {}

  // Kick off
  requestAnimationFrame(() => {
    setHeightToScroll();
    el.style.opacity = '1';
  });

  const cleanup = () => {
    try { roDuring?.disconnect?.(); } catch(_) {}
    el.style.height = 'auto';
    el.style.overflow = '';
    el.style.transition = '';
    // persistent observers for post-open growth
    attachGrowthObservers(el);
    // one extra nudge next frame for late additions
    requestAnimationFrame(() => { el.style.height = 'auto'; void el.offsetHeight; });
    setTransitioning(el, false);
  };

  // Normal end
  el.addEventListener('transitionend', (ev) => {
    if (ev.propertyName === 'height') cleanup();
  }, { once: true });

  // Fallback in case transitionend doesn’t fire (rare)
  setTimeout(() => { if (isTransitioning(el)) cleanup(); }, 600);
}


function animateClose(el) {
  if (!el) return;

  setTransitioning(el, true);

  // Stop growth observers so they don't flip height back to auto
  detachGrowthObservers(el);

  // From current natural height to 0
  el.style.overflow = 'hidden';
  const currentHeight = el.scrollHeight + 'px';
  el.style.height = currentHeight;

  // Force reflow
  el.offsetHeight;

  // Animate to 0
  el.style.transition = 'height 0.36s ease, opacity 0.28s ease';
  requestAnimationFrame(() => {
    el.style.height = '0px';
    el.style.opacity = '0';
  });

  const cleanup = () => {
    el.style.display = 'none';
    el._displayBefore = 'block';
    el.style.transition = '';
    el.style.height = '0px';
    el.style.opacity = '0';
    el.style.overflow = '';
    setTransitioning(el, false);
  };

  el.addEventListener('transitionend', (ev) => {
    if (ev.propertyName === 'height') cleanup();
  }, { once: true });

  // Fallback if content mutates during close and kills the transition
  setTimeout(() => { if (isTransitioning(el)) cleanup(); }, 600);
}

/* ---------- main toggle logic ---------- */

function buttonBarContents(id, functionCall) {
  const buttonId = `buttonBar-button-${id}`;
  const parent = document.getElementById('button-bar-content');
  if (!parent) return;

  let contentDiv = document.getElementById(`button-bar-div-${id}`);

  // guard: avoid toggling while animating
  if (contentDiv && isTransitioning(contentDiv)) return;

  // flip state
  buttonState[buttonId] = !buttonState[buttonId];
  const btn = document.getElementById(buttonId);
  if (btn) btn.style.backgroundColor = buttonState[buttonId] ? 'lightgreen' : '';

  if (buttonState[buttonId]) {
    // OPEN
    if (!contentDiv) {
      contentDiv = document.createElement('div');
      contentDiv.id = `button-bar-div-${id}`;
      contentDiv.style.display = 'none';
      contentDiv.style.height = '0px';
      contentDiv.style.opacity = '0';
      contentDiv.style.overflow = 'hidden';

      // build once
      const contents = typeof functionCall === 'function' ? functionCall() : null;
      if (contents instanceof Node || contents instanceof DocumentFragment) {
        contentDiv.appendChild(contents);
      } else if (typeof contents === 'string') {
        contentDiv.innerHTML = contents;
      }

      parent.appendChild(contentDiv);

      // your optional callbacks (unchanged)
      if (id === "10") initializeDocumentReadyFunctions && initializeDocumentReadyFunctions();
      if (id === "12") bouncyUpdate && bouncyUpdate();
      if (id === "15") updateColdNewNumber_edge_3 && updateColdNewNumber_edge_3();
      if (id === "13") comboUpdate && comboUpdate();
    } else if (contentDiv.style.display === 'none') {
      contentDiv.style.display = contentDiv._displayBefore || 'block';
    }
    animateOpen(contentDiv);
  } else {
    // CLOSE (no clearing here—avoid nuking nodes while closing)
    if (contentDiv) animateClose(contentDiv);
  }
}


// (Optional) expose a tiny nudge utility in case you want to call it manually
// after some very async draw (usually not required with the observers above).
window.__buttonBarNudge = function(elOrId){
  const el = typeof elOrId === 'string' ? document.getElementById(elOrId) : elOrId;
  if (!el) return;
  el.style.height = 'auto';
  void el.offsetHeight;
};

function isTransitioning(el){ return !!el && el.__transitioning === true; }
function setTransitioning(el, val){ if (el) el.__transitioning = !!val; }