/* Investra Documentation – Shared JavaScript */
document.addEventListener('DOMContentLoaded', function () {
  /* ── Sidebar toggle (mobile) ──────────────── */
  var toggle = document.getElementById('sidebarToggle');
  var sidebar = document.getElementById('docSidebar');
  var overlay = document.getElementById('sidebarOverlay');

  function openSidebar() {
    if (sidebar) sidebar.classList.add('open');
    if (overlay) overlay.classList.add('open');
    document.body.style.overflow = 'hidden';
  }
  function closeSidebar() {
    if (sidebar) sidebar.classList.remove('open');
    if (overlay) overlay.classList.remove('open');
    document.body.style.overflow = '';
  }
  if (toggle) toggle.addEventListener('click', openSidebar);
  if (overlay) overlay.addEventListener('click', closeSidebar);
  if (sidebar) {
    sidebar.querySelectorAll('a').forEach(function (a) {
      a.addEventListener('click', function () {
        if (window.innerWidth <= 1024) closeSidebar();
      });
    });
  }

  /* ── Sidebar: collapse ALL sections first ─── */
  document.querySelectorAll('.sidebar-heading').forEach(function (h) {
    h.classList.add('collapsed');
    h.addEventListener('click', function () {
      h.classList.toggle('collapsed');
    });
  });

  /* ── Active page highlight ────────────────── */
  var currentUrl = window.location.href.split('#')[0];
  
  document.querySelectorAll('.sidebar-items a').forEach(function (a) {
    if (a.href.split('#')[0] === currentUrl) {
      a.classList.add('active');
      // Expand ONLY the parent section
      var section = a.closest('.sidebar-section');
      if (section) {
        var heading = section.querySelector('.sidebar-heading');
        if (heading) {
          heading.classList.remove('collapsed');
          heading.classList.add('active');
        }
      }
    }
  });

  /* ── Copy buttons for code blocks ─────────── */
  document.querySelectorAll('pre').forEach(function (pre) {
    if (pre.querySelector('.copy-btn')) return;
    var code = pre.querySelector('code');
    if (!code) return;
    var btn = document.createElement('button');
    btn.className = 'copy-btn';
    btn.textContent = 'Copy';
    btn.addEventListener('click', function () {
      var text = code.textContent;
      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text).then(function () {
          btn.textContent = 'Copied!';
          setTimeout(function () { btn.textContent = 'Copy'; }, 1600);
        });
      }
    });
    pre.style.position = 'relative';
    pre.appendChild(btn);
  });
});
