/* Shared Mega-menu — used by App.jsx, SolucionPage.jsx, ServicioPage.jsx
   - hover open/close on desktop with hover-bridge + close timeout
   - tap toggle on touch devices
   - Esc closes; click-outside closes
   - basePath: "./" on home, "../" on sub-pages
*/

const SOLUCIONES_MENU = [
  { icon: 'file-text',     key: 'facturacion', title: 'Facturación y cobranzas',
    desc: 'Extracción de facturas, validación AFIP, recordatorios automáticos.',
    href: 'soluciones/facturacion.html' },
  { icon: 'shopping-cart', key: 'pedidos',     title: 'Operaciones de ecommerce',
    desc: 'Sincronización entre MercadoLibre, Tiendanube y catálogo interno.',
    href: 'soluciones/pedidos.html' },
  { icon: 'message-circle',key: 'clientes',    title: 'Atención al cliente',
    desc: 'Clasificación inteligente de consultas y respuestas automáticas.',
    href: 'soluciones/clientes.html' },
  { icon: 'bar-chart',     key: 'reportes',    title: 'Reportes y dashboards',
    desc: 'Datos consolidados, reportes ejecutivos generados por IA.',
    href: 'soluciones/reportes.html' },
];

const SERVICIOS_MENU = [
  { icon: 'globe',     key: 'pagina-web',              title: 'Página Web a medida',
    desc: 'Sitios profesionales con foco en conversión y performance.',
    href: 'servicios/pagina-web.html' },
  { icon: 'sparkles',  key: 'inteligencia-artificial', title: 'Inteligencia Artificial',
    desc: 'Agentes IA y workflows automatizados que ejecutan tareas reales.',
    href: 'servicios/inteligencia-artificial.html' },
  { icon: 'compass',   key: 'estrategia-comercial',    title: 'Estrategia Comercial',
    desc: 'Marca, redes y ads alineados. Te lo armamos y capacitamos a tu equipo.',
    href: 'servicios/estrategia-comercial.html' },
  { icon: 'workflow',  key: 'nuestras-soluciones',     title: 'Nuestras Soluciones',
    desc: 'Sistemas listos para resolver problemas específicos de back-office.',
    href: 'soluciones/index.html' },
];

const useMegaMenuMM = () => {
  const [open, setOpen] = React.useState(null); // null | 'soluciones' | 'servicios'
  const closeTimerRef = React.useRef(null);
  const wrapRef = React.useRef(null);

  const cancelClose = () => {
    if (closeTimerRef.current) {
      clearTimeout(closeTimerRef.current);
      closeTimerRef.current = null;
    }
  };
  const handleOpen = (which) => { cancelClose(); setOpen(which); };
  const handleScheduleClose = () => {
    cancelClose();
    closeTimerRef.current = setTimeout(() => setOpen(null), 160);
  };

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') setOpen(null); };
    const onClick = (e) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(null);
    };
    window.addEventListener('keydown', onKey);
    document.addEventListener('mousedown', onClick);
    return () => {
      window.removeEventListener('keydown', onKey);
      document.removeEventListener('mousedown', onClick);
    };
  }, []);

  return { open, setOpen, handleOpen, handleScheduleClose, cancelClose, wrapRef };
};

const MegamenuPanel = ({ items, isOpen, basePath, currentKey, onMouseEnter, onMouseLeave, onItemClick }) => (
  <div
    className={`megamenu ${isOpen ? 'is-open' : ''}`}
    role="menu"
    onMouseEnter={onMouseEnter}
    onMouseLeave={onMouseLeave}
    aria-hidden={!isOpen}
  >
    {items.map((item, i) => {
      const Icon = window.iconFromName ? window.iconFromName(item.icon) : (() => null);
      const isCurrent = item.key === currentKey;
      return (
        <a
          key={i}
          href={basePath + item.href}
          className={`megamenu-item ${isCurrent ? 'is-current' : ''}`}
          role="menuitem"
          tabIndex={isOpen ? 0 : -1}
          onClick={onItemClick}
        >
          <div className="megamenu-icon"><Icon size={18}/></div>
          <div className="megamenu-content">
            <h4 className="megamenu-title">{item.title}</h4>
            <p className="megamenu-desc">{item.desc}</p>
          </div>
          <Icons.ArrowUpRight size={14} className="megamenu-arrow"/>
        </a>
      );
    })}
  </div>
);

/* MegaTrigger renders the button + panel combo. Keep all hover logic local to a wrapper so each is self-contained. */
const MegaTrigger = ({ which, label, items, basePath, currentKey, isActive, ctx }) => {
  const isTouch = typeof window !== 'undefined' && window.matchMedia && window.matchMedia('(hover: none)').matches;
  const onMouseEnter = !isTouch ? () => ctx.handleOpen(which) : undefined;
  const onMouseLeave = !isTouch ? ctx.handleScheduleClose : undefined;
  const onPanelEnter = !isTouch ? ctx.cancelClose : undefined;
  const onClick = (e) => {
    if (isTouch) {
      e.preventDefault();
      ctx.setOpen(ctx.open === which ? null : which);
    }
  };

  return (
    <div className="nav-link-wrap"
         onMouseEnter={onMouseEnter}
         onMouseLeave={onMouseLeave}>
      <button
        className={`nav-trigger ${isActive ? 'is-active' : ''}`}
        onClick={onClick}
        aria-expanded={ctx.open === which}
        aria-haspopup="menu"
        type="button"
      >
        {label}
        <Icons.ChevronDown size={12} className="nav-caret"/>
      </button>
      <MegamenuPanel
        items={items}
        isOpen={ctx.open === which}
        basePath={basePath}
        currentKey={currentKey}
        onMouseEnter={onPanelEnter}
        onMouseLeave={onMouseLeave}
        onItemClick={() => ctx.setOpen(null)}
      />
    </div>
  );
};

window.SOLUCIONES_MENU = SOLUCIONES_MENU;
window.SERVICIOS_MENU = SERVICIOS_MENU;
window.useMegaMenuMM = useMegaMenuMM;
window.MegaTrigger = MegaTrigger;
