document.addEventListener("DOMContentLoaded", () => {
  "use strict";

  // --- Configuration & DOM Nodes ---
  const CONFIG = {
    classes: {
      active: "is-active",
      open: "open",
      hasChildren: "menu-item-has-children",
    },
    selectors: {
      menu: "ul.menu",
      hamburger: "#mobile-menu-toggle",
      subToggle: ".sub-menu-toggle",
      searchDialog: "#search-dialog",
      searchTrigger: ".lente-search",
      focusable:
        'a, button, input, textarea, select, [tabindex]:not([tabindex="-1"])',
    },
  };

  const nodes = {
    hamburger: document.querySelector(CONFIG.selectors.hamburger),
    menu: document.querySelector(CONFIG.selectors.menu),
    searchDialog: document.querySelector(CONFIG.selectors.searchDialog),
    searchTrigger: document.querySelector(CONFIG.selectors.searchTrigger),
  };

  /**
   * 1. Gestione Sub-Menu (Toggle Logic)
   * Separazione netta tra click sul link (navigazione) e click sul bottone (espansione)
   */
  const initSubMenus = () => {
    const toggles = document.querySelectorAll(CONFIG.selectors.subToggle);
    // Selezioniamo anche i link che hanno come href solo "#"
    const hashLinks = document.querySelectorAll(
      `.${CONFIG.classes.hasChildren} > a[href="#"]`,
    );
    
    // Debounce per prevenire doppi-click su mobile
    let lastToggleTime = 0;
    const DEBOUNCE_DELAY = 100; // ms

    const toggleLogic = (element, parentLi) => {
      // Debounce per prevenire più toggle in rapida successione
      const now = Date.now();
      if (now - lastToggleTime < DEBOUNCE_DELAY) {
        return;
      }
      lastToggleTime = now;

      const btn = parentLi.querySelector(CONFIG.selectors.subToggle);
      const isExpanded = btn?.getAttribute("aria-expanded") === "true";

      // Chiusura automatica dei fratelli (Accordion)
      const siblings = parentLi.parentElement.querySelectorAll(
        `.${CONFIG.classes.active}`,
      );
      siblings.forEach((sib) => {
        if (sib !== parentLi) {
          sib.classList.remove(CONFIG.classes.active);
          sib
            .querySelector(CONFIG.selectors.subToggle)
            ?.setAttribute("aria-expanded", "false");
        }
      });

      // Toggle stato corrente
      parentLi.classList.toggle(CONFIG.classes.active);
      btn?.setAttribute("aria-expanded", !isExpanded);
    };

    // Click sulla freccetta (con gestione touch)
    toggles.forEach((btn) => {
      btn.addEventListener("click", (e) => {
        e.preventDefault();
        e.stopPropagation();
        toggleLogic(btn, btn.closest(`.${CONFIG.classes.hasChildren}`));
      });
      
      // Supporto esplicito per touch su mobile
      btn.addEventListener("touchend", (e) => {
        e.preventDefault();
        e.stopPropagation();
        toggleLogic(btn, btn.closest(`.${CONFIG.classes.hasChildren}`));
      }, { passive: false });
    });

    // Click sul link "#" (permette di aprire il menu cliccando sul testo)
    hashLinks.forEach((link) => {
      link.addEventListener("click", (e) => {
        e.preventDefault();
        e.stopPropagation();
        toggleLogic(link, link.closest(`.${CONFIG.classes.hasChildren}`));
      });
    });
  };

  /**
   * 2. Mobile Navigation & Focus Trap
   */
  const initMobileMenu = () => {
    if (!nodes.hamburger || !nodes.menu) return;

    const toggleMenu = (forceClose = false) => {
      const isOpen = forceClose
        ? true
        : nodes.hamburger.getAttribute("aria-expanded") === "true";

      nodes.hamburger.setAttribute("aria-expanded", !isOpen);
      nodes.menu.classList.toggle(CONFIG.classes.open, !isOpen);
      nodes.hamburger.classList.toggle(CONFIG.classes.open, !isOpen);

      if (!isOpen) {
        document.addEventListener("keydown", handleFocusTrap);
        const firstLink = nodes.menu.querySelector(CONFIG.selectors.focusable);
        firstLink?.focus();
      } else {
        document.removeEventListener("keydown", handleFocusTrap);
        nodes.hamburger.focus();
      }
    };

    nodes.hamburger.addEventListener("click", () => toggleMenu());

    function handleFocusTrap(e) {
      if (e.key !== "Tab") return;

      const focusables = nodes.menu.querySelectorAll(
        CONFIG.selectors.focusable,
      );
      const first = focusables[0];
      const last = focusables[focusables.length - 1];

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

  /**
   * 3. Search Dialog Management
   * Sostituisce la logica jQuery con l'API nativa <dialog>
   */
  const initSearch = () => {
    if (!nodes.searchDialog || !nodes.searchTrigger) return;

    nodes.searchTrigger.addEventListener("click", (e) => {
      e.preventDefault();
      nodes.searchDialog.showModal();

      // Timeout minimo per garantire il rendering del dialog prima del focus
      setTimeout(() => {
        const input = nodes.searchDialog.querySelector("input");
        input?.focus();
      }, 50);
    });

    // Chiusura al click sull'overlay (background del dialog)
    nodes.searchDialog.addEventListener("click", (e) => {
      if (e.target === nodes.searchDialog) {
        nodes.searchDialog.close();
      }
    });
  };

  /**
   * 4. Global Click Listener
   * Chiude i menu aperti se si clicca all'esterno
   */
  const initOutsideClick = () => {
    document.addEventListener("click", (e) => {
      if (
        !e.target.closest(`.${CONFIG.classes.hasChildren}`) &&
        !e.target.closest(CONFIG.selectors.hamburger)
      ) {
        document.querySelectorAll(`.${CONFIG.classes.active}`).forEach((el) => {
          el.classList.remove(CONFIG.classes.active);
          el.querySelector(CONFIG.selectors.subToggle)?.setAttribute(
            "aria-expanded",
            "false",
          );
        });
      }
    });
  };

  // Inizializzazione moduli
  initSubMenus();
  initMobileMenu();
  initSearch();
  initOutsideClick();
});
