(function () {
  'use strict';

  const backdrop = document.querySelector('[data-mobile-drawer-backdrop]');
  const pickerDrawer = document.querySelector('[data-picker-drawer]');
  const metaDrawer = document.querySelector('[data-meta-drawer]');
  const commentsAside = document.querySelector('[data-comments-aside]');
  const pickerToggle = document.querySelector('[data-toggle-picker]');
  const metaToggle = document.querySelector('[data-toggle-meta]');
  const pickerClose = document.querySelector('[data-close-picker]');
  const metaClose = document.querySelector('[data-close-meta]');

  function anyDrawerOpen() {
    return Boolean(
      pickerDrawer?.classList.contains('is-open') ||
      metaDrawer?.classList.contains('is-open') ||
      commentsAside?.classList.contains('is-open')
    );
  }

  function updateBackdrop() {
    document.body.classList.toggle('drawer-open', anyDrawerOpen());
  }

  function setPickerOpen(open) {
    if (!pickerDrawer) return;
    pickerDrawer.classList.toggle('is-open', open);
    if (pickerToggle) pickerToggle.setAttribute('aria-expanded', open ? 'true' : 'false');
    updateBackdrop();
  }

  function setMetaOpen(open) {
    if (!metaDrawer) return;
    metaDrawer.classList.toggle('is-open', open);
    if (metaToggle) metaToggle.setAttribute('aria-expanded', open ? 'true' : 'false');
    updateBackdrop();
  }

  function closeAllDrawers() {
    setPickerOpen(false);
    setMetaOpen(false);
    if (commentsAside) {
      commentsAside.classList.remove('is-open');
      const toggle = document.querySelector('[data-toggle-comments]');
      if (toggle) toggle.setAttribute('aria-expanded', 'false');
    }
    updateBackdrop();
  }

  if (pickerToggle) {
    pickerToggle.addEventListener('click', () => {
      const willOpen = !pickerDrawer?.classList.contains('is-open');
      closeAllDrawers();
      setPickerOpen(willOpen);
    });
  }

  if (metaToggle) {
    metaToggle.addEventListener('click', () => {
      const willOpen = !metaDrawer?.classList.contains('is-open');
      closeAllDrawers();
      setMetaOpen(willOpen);
    });
  }

  if (pickerClose) pickerClose.addEventListener('click', () => setPickerOpen(false));
  if (metaClose) metaClose.addEventListener('click', () => setMetaOpen(false));

  if (backdrop) {
    backdrop.addEventListener('click', closeAllDrawers);
  }

  // Close drawers on Escape key
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') closeAllDrawers();
  });

  // Close action dropdowns when clicking outside
  document.addEventListener('click', (e) => {
    document.querySelectorAll('.document-actions-dropdown[open]').forEach((details) => {
      if (!details.contains(e.target)) {
        details.removeAttribute('open');
      }
    });
  });
})();
