document.addEventListener('DOMContentLoaded', function () {
  var userMenuButton = document.getElementById('user-menu-button');
  var profileMenuDropdown =
    document.querySelector('.profile-menu__dropdown') ||
    document.querySelector('.wp-block-memberpress-pro-profile-menu__dropdown');
  var mobileMenuButton =
    document.querySelector('.profile-menu__button.--is-mobile') ||
    document.querySelector('.wp-block-memberpress-pro-profile-menu__button.--is-mobile');
  var meprAccountNav = document.getElementById('mepr-account-nav');
  var clAccount = document.querySelector('.mepr-rl-account');
  var isClAccountDrawer =
    clAccount && meprAccountNav && clAccount.contains(meprAccountNav);

  var mobileOverlay = null;

  function ensureMobileDrawerCloseIcon() {
    if (!isClAccountDrawer || !mobileMenuButton) {
      return;
    }
    if (mobileMenuButton.querySelector('.mepr-account-mobile-menu-close-icon')) {
      return;
    }
    var ns = 'http://www.w3.org/2000/svg';
    var closeSvg = document.createElementNS(ns, 'svg');
    closeSvg.setAttribute('class', 'mepr-account-mobile-menu-close-icon mepr-rl-shell-mobile-menu-close-icon');
    closeSvg.setAttribute('fill', 'none');
    closeSvg.setAttribute('viewBox', '0 0 24 24');
    closeSvg.setAttribute('stroke', 'currentColor');
    closeSvg.setAttribute('stroke-width', '2');
    closeSvg.setAttribute('aria-hidden', 'true');
    var p1 = document.createElementNS(ns, 'path');
    p1.setAttribute('stroke-linecap', 'round');
    p1.setAttribute('stroke-linejoin', 'round');
    p1.setAttribute('d', 'M6 18L18 6M6 6l12 12');
    closeSvg.appendChild(p1);
    mobileMenuButton.appendChild(closeSvg);
  }

  function toggleProfileDropdown() {
    if (profileMenuDropdown) {
      profileMenuDropdown.classList.toggle('is-open');
    }
  }

  function closeProfileDropdown() {
    if (profileMenuDropdown) {
      profileMenuDropdown.classList.remove('is-open');
    }
  }

  function ensureOverlay() {
    if (!isClAccountDrawer || mobileOverlay) {
      return mobileOverlay;
    }
    mobileOverlay = document.createElement('div');
    mobileOverlay.className = 'mepr-account-mobile-overlay mepr-rl-shell-mobile-overlay';
    mobileOverlay.setAttribute('aria-hidden', 'true');
    document.body.appendChild(mobileOverlay);
    mobileOverlay.addEventListener('click', closeClAccountDrawer);
    return mobileOverlay;
  }

  function mergeProfileQuicklinks() {
    if (!isClAccountDrawer || !meprAccountNav) {
      return;
    }
    if (meprAccountNav.querySelector('.mepr-account-mobile-quicklinks')) {
      return;
    }
    var dropdown =
      document.querySelector('.profile-menu__dropdown') ||
      document.querySelector('.wp-block-memberpress-pro-profile-menu__dropdown');
    if (!dropdown) {
      return;
    }
    var links = dropdown.querySelectorAll('a[href]');
    if (!links.length) {
      return;
    }
    var wrap = document.createElement('div');
    wrap.className = 'mepr-account-mobile-quicklinks mepr-rl-shell-mobile-quicklinks';
    wrap.setAttribute('role', 'group');

    links.forEach(function (a) {
      wrap.appendChild(a.cloneNode(true));
    });

    var ul = meprAccountNav.querySelector('ul');
    if (ul) {
      meprAccountNav.insertBefore(wrap, ul);
    } else {
      meprAccountNav.insertBefore(wrap, meprAccountNav.firstChild);
    }
  }

  function removeMobileQuicklinks() {
    if (!meprAccountNav) {
      return;
    }
    var quick = meprAccountNav.querySelector('.mepr-account-mobile-quicklinks');
    if (quick) {
      quick.remove();
    }
  }

  function openClAccountDrawer() {
    if (!meprAccountNav) {
      return;
    }
    mergeProfileQuicklinks();
    var ov = ensureOverlay();
    meprAccountNav.classList.add('open');
    document.body.classList.add('mepr-rl-account-mobile-nav-open', 'mepr-rl-shell-mobile-nav-open');
    if (ov) {
      ov.classList.add('is-visible');
    }
    if (mobileMenuButton) {
      mobileMenuButton.setAttribute('aria-expanded', 'true');
      mobileMenuButton.setAttribute('aria-label', 'Close menu');
    }
  }

  function closeClAccountDrawer() {
    if (!meprAccountNav) {
      return;
    }
    var wasOpen = meprAccountNav.classList.contains('open');
    meprAccountNav.classList.remove('open');
    if (mobileOverlay) {
      mobileOverlay.classList.remove('is-visible');
    }
    if (mobileMenuButton) {
      mobileMenuButton.setAttribute('aria-expanded', 'false');
      mobileMenuButton.setAttribute('aria-label', 'Open menu');
    }

    /* Defer body-class removal + quicklinks cleanup until the slide-out
     * transition completes. Removing them synchronously drops the header
     * z-index (shell.css raises it to 100000 only while the body class is
     * set) and pops the cloned profile links out of the DOM — both happen
     * at frame 0 while the drawer is still at translateX(0), which is the
     * "colored flicker at the top" during slide-out. */
    var doCleanup = function () {
      if (meprAccountNav.classList.contains('open')) {
        return; /* user re-opened mid-slide-out */
      }
      document.body.classList.remove('mepr-rl-account-mobile-nav-open', 'mepr-rl-shell-mobile-nav-open');
      removeMobileQuicklinks();
    };

    if (wasOpen && window.innerWidth < 840) {
      var onSlideOutEnd = function (ev) {
        if (ev.target !== meprAccountNav || ev.propertyName !== 'transform') {
          return;
        }
        meprAccountNav.removeEventListener('transitionend', onSlideOutEnd);
        doCleanup();
      };
      meprAccountNav.addEventListener('transitionend', onSlideOutEnd);
    } else {
      /* Desktop resize handler or already-closed: nothing to animate. */
      doCleanup();
    }
  }

  function toggleClAccountDrawer() {
    if (meprAccountNav.classList.contains('open')) {
      closeClAccountDrawer();
    } else {
      openClAccountDrawer();
    }
  }

  if (userMenuButton && profileMenuDropdown) {
    userMenuButton.addEventListener('click', toggleProfileDropdown);

    document.addEventListener('click', function (event) {
      var isFromMenu =
        userMenuButton.contains(event.target) ||
        profileMenuDropdown.contains(event.target) ||
        (mobileMenuButton && mobileMenuButton.contains(event.target));
      if (!isFromMenu) {
        closeProfileDropdown();
      }
    });
  }

  if (mobileMenuButton) {
    if (isClAccountDrawer && meprAccountNav) {
      ensureMobileDrawerCloseIcon();
      mobileMenuButton.setAttribute('aria-label', 'Open menu');
      mobileMenuButton.addEventListener(
        'click',
        function (e) {
          e.preventDefault();
          e.stopImmediatePropagation();
          toggleClAccountDrawer();
        },
        true
      );

      document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && meprAccountNav.classList.contains('open')) {
          closeClAccountDrawer();
        }
      });

      meprAccountNav.addEventListener('click', function (e) {
        var t = e.target;
        if (t && t.closest && t.closest('a') && meprAccountNav.classList.contains('open')) {
          closeClAccountDrawer();
        }
      });

      window.addEventListener('resize', function () {
        /* Always reset drawer state when returning to desktop (avoids stray body/overlay class). */
        if (window.innerWidth >= 840) {
          closeClAccountDrawer();
        }
      });
    } else if (meprAccountNav) {
      mobileMenuButton.addEventListener('click', function () {
        meprAccountNav.classList.toggle('open');
      });
    } else if (profileMenuDropdown) {
      /* No drawer / no account nav (e.g. Courses, Login, or any FSE page
       * that ships the profile-menu without an account or coaching drawer):
       * the mobile button now shows the avatar, so reuse the desktop
       * dropdown handler so users on these routes can still reach
       * Account / Logout / etc. Coaching pages bind their own drawer
       * handler in capture phase with stopImmediatePropagation, so this
       * bubble-phase listener is naturally suppressed there. */
      mobileMenuButton.addEventListener('click', toggleProfileDropdown);
    }
  }
});
