/* =============================================================
   main.js – Mohi Theme
   ============================================================= */

/* ---------------------------------------------------------------
   1. Scroll To Top
--------------------------------------------------------------- */
document.addEventListener('DOMContentLoaded', function () {
  var btn = document.getElementById('scrollToTopBtn');
  if (!btn) return;

  window.addEventListener('scroll', function () {
    btn.style.display =
      (document.body.scrollTop > 200 || document.documentElement.scrollTop > 200)
        ? 'block' : 'none';
  });

  btn.addEventListener('click', function () {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  });
});

/* ---------------------------------------------------------------
   2. Mobile Search Toggle
--------------------------------------------------------------- */
document.addEventListener('DOMContentLoaded', function () {
  var searchCollapse = document.getElementById('searchCollapse');
  var offcanvasNav   = document.getElementById('offcanvasNav');
  var searchToggle   = document.getElementById('searchToggle');

  if (!searchCollapse || !searchToggle) return;

  var searchIcon   = searchToggle.querySelector('.icon-search');
  var closeIcon    = searchToggle.querySelector('.icon-close');
  var isSearchOpen = false;

  searchCollapse.addEventListener('show.bs.collapse', function () {
    isSearchOpen = true;
    if (searchIcon) searchIcon.classList.add('d-none');
    if (closeIcon)  closeIcon.classList.remove('d-none');
    searchToggle.setAttribute('aria-expanded', 'true');
    var input = searchCollapse.querySelector('input[type="search"], input[type="text"]');
    if (input) { setTimeout(function () { input.focus(); }, 150); }
  });

  searchCollapse.addEventListener('hide.bs.collapse', function () {
    isSearchOpen = false;
    if (closeIcon)  closeIcon.classList.add('d-none');
    if (searchIcon) searchIcon.classList.remove('d-none');
    searchToggle.setAttribute('aria-expanded', 'false');
    searchToggle.focus();
  });

  document.addEventListener('keydown', function (e) {
    if (!isSearchOpen) return;

    var input  = searchCollapse.querySelector('input[type="search"], input[type="text"]');
    var submit = searchCollapse.querySelector('button[type="submit"], input[type="submit"]');
    var ring   = [searchToggle, input, submit].filter(Boolean);
    var idx    = ring.indexOf(document.activeElement);

    if (e.key === 'Escape') {
      e.preventDefault();
      var bsC = typeof bootstrap !== 'undefined'
        ? bootstrap.Collapse.getInstance(searchCollapse) : null;
      if (bsC) bsC.hide();
      return;
    }

    if (e.key !== 'Tab') return;
    if (idx === -1) return;

    if (!e.shiftKey) {
      if (idx === ring.length - 1) { e.preventDefault(); ring[0].focus(); }
    } else {
      if (idx === 0) { e.preventDefault(); ring[ring.length - 1].focus(); }
    }
  });

  if (offcanvasNav && typeof bootstrap !== 'undefined') {
    offcanvasNav.addEventListener('show.bs.offcanvas', function () {
      var bsC = bootstrap.Collapse.getInstance(searchCollapse);
      if (bsC) bsC.hide();
    });
  }
});

/* ---------------------------------------------------------------
   3. Desktop hover dropdowns
--------------------------------------------------------------- */
document.addEventListener('DOMContentLoaded', function () {
  if (window.innerWidth >= 992) {
    document.querySelectorAll('.nav-link[data-bs-toggle="dropdown"]').forEach(function (el) {
      el.removeAttribute('data-bs-toggle');
    });
  }
});

/* ---------------------------------------------------------------
   4. Submenu open / close
--------------------------------------------------------------- */
document.addEventListener('DOMContentLoaded', function () {

 
  function getDropdownMenu(el) {
    var li = el.parentElement;
    while (li && !li.classList.contains('dropdown')) {
      li = li.parentElement;
    }
    return li ? li.querySelector(':scope > .dropdown-menu') : null;
  }

  function getMenuItems(menu) {
    return Array.from(menu.children).reduce(function (acc, li) {
      var link = li.querySelector(':scope > a.dropdown-item, :scope > a[role="menuitem"]');
      if (link && link.offsetParent !== null) acc.push(link);
      return acc;
    }, []);
  }

  function openMenu(menu, btn) {
    menu.classList.add('show');
    if (btn) btn.setAttribute('aria-expanded', 'true');
  }

  function closeMenu(menu, btn) {
    menu.classList.remove('show');
    if (btn) btn.setAttribute('aria-expanded', 'false');
    menu.querySelectorAll('.dropdown-menu.show').forEach(function (sub) {
      sub.classList.remove('show');
      var nestedBtn = sub.closest('.dropdown') &&
        sub.closest('.dropdown').querySelector('.mohi-submenu-toggle');
      if (nestedBtn) nestedBtn.setAttribute('aria-expanded', 'false');
    });
  }

  function closeAllMenus() {
    document.querySelectorAll('.dropdown-menu.show').forEach(function (m) {
      var li   = m.closest('.dropdown');
      var link = li ? li.querySelector(':scope > .mohi-nav-wrap > .nav-link, :scope > .nav-link') : null;
      var btn  = li ? li.querySelector(':scope > .mohi-nav-wrap > .mohi-submenu-toggle') : null;
      m.classList.remove('show');
      if (link) link.setAttribute('aria-expanded', 'false');
      if (btn)  btn.setAttribute('aria-expanded', 'false');
    });
  }

  /* ── Mobile: tap nav-link toggles submenu ── */
  document.querySelectorAll('.nav-item.dropdown > .mohi-nav-wrap > .nav-link').forEach(function (link) {
    link.addEventListener('click', function (e) {
      if (window.innerWidth >= 992) return;
      e.preventDefault();
      e.stopPropagation();
      var menu   = getDropdownMenu(link);
      if (!menu) return;
      var btn    = link.closest('.dropdown').querySelector(':scope > .mohi-nav-wrap > .mohi-submenu-toggle');
      var isOpen = menu.classList.contains('show');
      closeAllMenus();
      if (!isOpen) { openMenu(menu, btn); }
    });
  });

  /* ── Desktop: nav-link keyboard handler ── */
  document.querySelectorAll('.nav-item.dropdown > .mohi-nav-wrap > .nav-link').forEach(function (link) {
    link.addEventListener('keydown', function (e) {
      if (window.innerWidth < 992) return;
      var li   = link.closest('.dropdown');
      var btn  = li ? li.querySelector(':scope > .mohi-nav-wrap > .mohi-submenu-toggle') : null;
      var menu = getDropdownMenu(link);

      /* Tab forward → focus toggle button (do NOT open menu yet) */
      if (!e.shiftKey && e.key === 'Tab') {
        if (btn) {
          e.preventDefault();
          btn.focus();
        }
        return;
      }

      /* Shift+Tab → close menu if open, let browser go back naturally */
      if (e.shiftKey && e.key === 'Tab') {
        if (menu) closeMenu(menu, btn);
        return;
      }

      /* ArrowDown → open and focus first item */
      if (e.key === 'ArrowDown') {
        e.preventDefault();
        if (menu) {
          var items = getMenuItems(menu);
          if (items.length) { openMenu(menu, btn); items[0].focus(); }
        }
        return;
      }

      if (e.key === 'Escape') {
        if (menu) closeMenu(menu, btn);
        link.focus();
      }
    });
  });

  /* ── Toggle button: click + keyboard ── */
  document.querySelectorAll('.mohi-submenu-toggle').forEach(function (btn) {

    /* Click (mouse or tap on mobile) */
    btn.addEventListener('click', function (e) {
      e.preventDefault();
      e.stopPropagation();
      var menu   = getDropdownMenu(btn);
      if (!menu) return;
      var isOpen = menu.classList.contains('show');

      var parentLi = btn.closest('li.dropdown');
      if (parentLi && parentLi.parentElement) {
        parentLi.parentElement.querySelectorAll(':scope > li.dropdown > .dropdown-menu.show').forEach(function (m) {
          if (m !== menu) {
            var siblingBtn = m.closest('.dropdown').querySelector('.mohi-submenu-toggle');
            closeMenu(m, siblingBtn);
          }
        });
      }

      if (!isOpen) {
        openMenu(menu, btn);
        if (window.innerWidth >= 992) {
          var first = getMenuItems(menu)[0];
          if (first) first.focus();
        } else {
          btn.focus();
        }
      } else {
        closeMenu(menu, btn);
        btn.focus();
      }
    });

    /* Keyboard on the toggle button */
    btn.addEventListener('keydown', function (e) {
      var li      = btn.closest('.dropdown');
      var menu    = getDropdownMenu(btn);
      var prevFocus = li ? (
        li.querySelector(':scope > .mohi-nav-wrap > .nav-link') ||
        li.querySelector(':scope > .mohi-nav-wrap > .dropdown-item')
      ) : null;
      if (!menu) return;
      var items = getMenuItems(menu);

      /* Enter / Space → toggle menu */
      if (e.key === 'Enter' || e.key === ' ') {
        e.preventDefault();
        var isOpen = menu.classList.contains('show');
        if (!isOpen) {
          openMenu(menu, btn);
          if (items[0]) items[0].focus();
        } else {
          closeMenu(menu, btn);
          btn.focus();
        }
        return;
      }

      /* Tab forward → open menu, go to first item */
      if (!e.shiftKey && e.key === 'Tab') {
        if (items.length) {
          e.preventDefault();
          openMenu(menu, btn);
          items[0].focus();
        }
        return;
      }

      /* Shift+Tab → go back to nav-link/dropdown-item, close menu */
      if (e.shiftKey && e.key === 'Tab') {
        e.preventDefault();
        closeMenu(menu, btn);
        if (prevFocus) prevFocus.focus();
        return;
      }

      /* ArrowDown → open and focus first */
      if (e.key === 'ArrowDown') {
        e.preventDefault();
        openMenu(menu, btn);
        if (items[0]) items[0].focus();
        return;
      }

      /* Escape → close, focus back */
      if (e.key === 'Escape') {
        closeMenu(menu, btn);
        if (prevFocus) prevFocus.focus();
        else btn.focus();
      }
    });
  });

  /* ── Tab / Shift+Tab / Arrow keys inside submenu items ── */
  document.querySelectorAll('.dropdown-menu').forEach(function (menu) {
    var li  = menu.closest('.dropdown');
    var btn = li ? li.querySelector(':scope > .mohi-nav-wrap > .mohi-submenu-toggle') : null;
    var prevFocus = li ? (
      li.querySelector(':scope > .mohi-nav-wrap > .nav-link') ||
      li.querySelector(':scope > .mohi-nav-wrap > .dropdown-item')
    ) : null;

    menu.querySelectorAll('a.dropdown-item, a[role="menuitem"]').forEach(function (item) {
      item.addEventListener('keydown', function (e) {
        var items = getMenuItems(menu);
        var idx   = items.indexOf(item);

        /* Tab forward */
        if (e.key === 'Tab' && !e.shiftKey) {

          var itemLi        = item.closest('li.dropdown');
          var nestedToggle  = itemLi
            ? itemLi.querySelector(':scope > .mohi-nav-wrap > .mohi-nested-toggle')
            : null;

          if (nestedToggle) {
            e.preventDefault();
            nestedToggle.focus();
            return;
          }

          if (idx === items.length - 1) {
            /* Last item → close menu, browser Tabs to next nav-link */
            closeMenu(menu, btn);
          } else {
            e.preventDefault();
            items[idx + 1].focus();
          }
          return;
        }

        /* Shift+Tab backward */
        if (e.key === 'Tab' && e.shiftKey) {
          if (idx === 0) {
            /* First item → go back to toggle button */
            e.preventDefault();
            closeMenu(menu, btn);
            if (btn) btn.focus();
            else if (prevFocus) prevFocus.focus();
          } else {
            e.preventDefault();
            items[idx - 1].focus();
          }
          return;
        }

        /* ArrowDown */
        if (e.key === 'ArrowDown') {
          e.preventDefault();
          var next = items[idx + 1] || items[0];
          if (next) next.focus();
          return;
        }

        /* ArrowUp */
        if (e.key === 'ArrowUp') {
          e.preventDefault();
          if (idx > 0) {
            items[idx - 1].focus();
          } else {
            closeMenu(menu, btn);
            if (btn) btn.focus();
            else if (prevFocus) prevFocus.focus();
          }
          return;
        }

        if (e.key === 'ArrowRight') {
          var itemLi2       = item.closest('li.dropdown');
          var nestedToggle2 = itemLi2
            ? itemLi2.querySelector(':scope > .mohi-nav-wrap > .mohi-nested-toggle')
            : null;
          var nestedMenu    = itemLi2
            ? itemLi2.querySelector(':scope > .dropdown-menu')
            : null;

          if (nestedMenu) {
            e.preventDefault();
            openMenu(nestedMenu, nestedToggle2);
            var nestedItems = getMenuItems(nestedMenu);
            if (nestedItems[0]) nestedItems[0].focus();
          }
          return;
        }

        if (e.key === 'ArrowLeft') {
          var parentMenu = item.closest('.dropdown-menu.dropdown-submenu');
          if (parentMenu) {
            var parentLi2     = parentMenu.closest('li.dropdown');
            var parentBtn     = parentLi2
              ? parentLi2.querySelector(':scope > .mohi-nav-wrap > .mohi-nested-toggle')
              : null;
            var parentItem    = parentLi2
              ? parentLi2.querySelector(':scope > .mohi-nav-wrap > .dropdown-item')
              : null;
            e.preventDefault();
            closeMenu(parentMenu, parentBtn);
            if (parentItem) parentItem.focus();
            else if (parentBtn) parentBtn.focus();
          }
          return;
        }

        /* Escape */
        if (e.key === 'Escape') {
          closeMenu(menu, btn);
          if (btn) btn.focus();
          else if (prevFocus) prevFocus.focus();
        }
      });
    });
  });

  /* ── Close on outside click ── */
  document.addEventListener('click', function (e) {
    if (!e.target.closest('.dropdown')) closeAllMenus();
  });

  
  document.querySelectorAll('.nav-item.dropdown').forEach(function (topLi) {
    topLi.addEventListener('focusout', function (e) {
      
      setTimeout(function () {
        if (!topLi.contains(document.activeElement)) {
          
          topLi.querySelectorAll('.dropdown-menu.show').forEach(function (m) {
            var li2 = m.closest('.dropdown');
            var b   = li2 ? li2.querySelector(':scope > .mohi-nav-wrap > .mohi-submenu-toggle') : null;
            m.classList.remove('show');
            if (b) b.setAttribute('aria-expanded', 'false');
          });
          
          var topBtn = topLi.querySelector(':scope > .mohi-nav-wrap > .mohi-submenu-toggle');
          if (topBtn) topBtn.setAttribute('aria-expanded', 'false');
        }
      }, 0);
    });
  });
});

/* ---------------------------------------------------------------
   5. Offcanvas – Tab to close
--------------------------------------------------------------- */
document.addEventListener('DOMContentLoaded', function () {
  var offcanvas = document.getElementById('offcanvasNav');
  if (!offcanvas) return;

  offcanvas.addEventListener('shown.bs.offcanvas', function () {
    var items = getFocusable(offcanvas);
    if (items.length) items[0].focus();
  });

  offcanvas.addEventListener('keydown', function (e) {
    if (e.key !== 'Tab') return;
    var items = getFocusable(offcanvas);
    if (!items.length) return;
    var first = items[0];
    var last  = items[items.length - 1];

    if (!e.shiftKey && document.activeElement === last) {
      e.preventDefault();
      hideOffcanvas();
    } else if (e.shiftKey && document.activeElement === first) {
      e.preventDefault();
      hideOffcanvas();
    }
  });

  function getFocusable(el) {
    return Array.from(el.querySelectorAll(
      'a[href], button:not([disabled]), input, select, textarea, [tabindex]:not([tabindex="-1"])'
    )).filter(function (n) { return n.offsetParent !== null; });
  }

  function hideOffcanvas() {
    if (typeof bootstrap !== 'undefined') {
      var oc = bootstrap.Offcanvas.getInstance(offcanvas);
      if (oc) oc.hide();
    }
  }
});