document.addEventListener('DOMContentLoaded', function () {
  const toggle = document.querySelector('.nav-toggle');
  const menu = document.querySelector(toggle?.dataset.target || '#site-menu');
  const actions = document.querySelector('.site-actions');

  function closeMenu() {
    if (!menu || !toggle) return;
    menu.classList.remove('open');
    actions?.classList.remove('open');
    toggle.setAttribute('aria-expanded', 'false');
  }

  if (toggle && menu) {
    toggle.addEventListener('click', function () {
      const isOpen = menu.classList.toggle('open');
      actions?.classList.toggle('open', isOpen);
      toggle.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
    });

    menu.querySelectorAll('a').forEach(function (link) {
      link.addEventListener('click', function () {
        if (window.innerWidth <= 991) closeMenu();
      });
    });

    actions?.querySelectorAll('a').forEach(function (link) {
      link.addEventListener('click', function () {
        if (window.innerWidth <= 991) closeMenu();
      });
    });

    document.addEventListener('click', function (event) {
      if (window.innerWidth > 991) return;
      const insideNav = event.target.closest('.site-nav');
      if (!insideNav && menu.classList.contains('open')) closeMenu();
    });

    window.addEventListener('resize', function () {
      if (window.innerWidth > 991) {
        menu.classList.remove('open');
        actions?.classList.remove('open');
        toggle.setAttribute('aria-expanded', 'false');
      }
    });
  }

  document.querySelectorAll('.bottom-nav .nav-item').forEach(function (link) {
    link.addEventListener('click', function () {
      link.style.transform = 'scale(0.97)';
      setTimeout(function () { link.style.transform = ''; }, 140);
    });
  });

  if (window.jQuery) {
    const $ = window.jQuery;

    if ($.fn.select2) {
      $('.searchable-select, .select2').each(function () {
        const $el = $(this);
        if (!$el.hasClass('select2-hidden-accessible')) {
          $el.select2({
            theme: 'bootstrap-5',
            width: '100%',
            dir: 'rtl',
            language: 'fa'
          });
        }
      });
    }

    if ($.fn.venobox) {
      $('.venobox').venobox({ numeratio: true, border: '12px' });
      $('.venoboxvid').venobox({ bgcolor: '#000', spinner: 'cube-grid' });
      $('.venoboxframe').venobox({ border: '8px', overlayColor: 'rgba(47,36,28,0.75)' });
    }
  }
});

function copyPoetry() {
  const poetryText = document.querySelector('.poetry-content');
  if (!poetryText || !navigator.clipboard) return;
  navigator.clipboard.writeText(poetryText.innerText).then(function () {
    const btn = document.querySelector('.copy-btn');
    if (!btn) return;
    btn.classList.add('copied');
    setTimeout(function () { btn.classList.remove('copied'); }, 1500);
  }).catch(function () {});
}
