// sidebar.js
$(function () {
  const $sidebar = $('.sidebar');
  const $body = $('body');
  const $toggle = $('#toggleSidebar');

  function toggleSidebar(forceClose = false) {
    if (forceClose) {
      $sidebar.removeClass('active');
      $body.removeClass('sidebar-open');
      $toggle.attr('aria-expanded', 'false');
      return;
    }

    const isActive = $sidebar.hasClass('active');
    $sidebar.toggleClass('active', !isActive);
    $body.toggleClass('sidebar-open', !isActive);
    $toggle.attr('aria-expanded', String(!isActive));
  }

  // 🔹 Toggle hamburger
  $(document).on('click', '#toggleSidebar', function (e) {
    e.stopPropagation();
    toggleSidebar();
  });

  // 🔹 Klik di luar sidebar → tutup
  $(document).on('click', function (e) {
    if (
      window.innerWidth <= 767.98 &&
      $sidebar.hasClass('active') &&
      !$(e.target).closest('.sidebar, #toggleSidebar').length
    ) {
      toggleSidebar(true);
    }
  });

  // 🔹 Klik link sidebar → tutup hanya jika bukan collapse toggle
  $sidebar.on('click', '.nav-link', function (e) {
    const $this = $(this);
    const dt = $this.attr('data-toggle');
    const dbs = $this.attr('data-bs-toggle');
    const href = $this.attr('href') || '';
    const isCollapseToggle =
      (dt && dt === 'collapse') ||
      (dbs && dbs === 'collapse') ||
      href.indexOf('#collapse-') === 0;

    if (window.innerWidth <= 767.98 && !isCollapseToggle) {
      toggleSidebar(true);
    }
  });

  // 🔹 MutationObserver dengan debounce
  let rebindTimeout;
  const observer = new MutationObserver(() => {
    clearTimeout(rebindTimeout);
    rebindTimeout = setTimeout(() => {
      if (!$('#toggleSidebar').data('bound')) {
        $('#toggleSidebar')
          .data('bound', true)
          .off('click')
          .on('click', function (e) {
            e.stopPropagation();
            toggleSidebar();
          });
      }
    }, 100);
  });

  observer.observe(document.getElementById('crud-content'), {
    childList: true,
    subtree: true,
  });

  // 🔹 Reset jika ukuran layar besar
  $(window).on('resize', function () {
    if (window.innerWidth > 767.98) toggleSidebar(true);
  });
});
