// Nav.jsx — sticky top nav with backdrop blur.

const navStyles = {
  outer: {
    position: 'sticky',
    top: 0,
    zIndex: 100,
    background: 'rgba(246, 244, 238, 0.85)',
    backdropFilter: 'blur(12px)',
    WebkitBackdropFilter: 'blur(12px)',
    borderBottom: '1px solid rgba(42, 26, 7,.08)',
  },
  inner: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: '14px 0',
  },
  logo: { display: 'block', height: 50, width: 'auto' },
  links: {
    display: 'flex',
    gap: 28,
    fontSize: 14,
    fontWeight: 500,
    alignItems: 'center',
  },
  right: { display: 'flex', alignItems: 'center', gap: 16 },
  dropdownWrap: { position: 'relative' },
  dropdownTrigger: {
    display: 'inline-flex', alignItems: 'center', gap: 4,
    backgroundColor: 'transparent', border: 'none', cursor: 'pointer',
    font: 'inherit', color: 'inherit',
    paddingTop: 0, paddingLeft: 0, paddingRight: 0, paddingBottom: 2,
  },
  dropdownChevron: { transition: 'transform 160ms var(--ease)' },
  dropdownPanel: {
    position: 'absolute', top: 'calc(100% + 14px)', left: 0,
    minWidth: 250, background: '#fff', border: '1px solid var(--ink-900)',
    boxShadow: '4px 4px 0 0 var(--amber-500)', padding: 8,
    display: 'flex', flexDirection: 'column', gap: 2, zIndex: 110,
  },
  dropdownAll: {
    padding: '10px 12px', fontSize: 12.5, color: 'var(--blue-700)',
    textDecoration: 'none', borderTop: '1px solid rgba(42,26,7,.10)',
    marginTop: 4, paddingTop: 12,
    display: 'flex', alignItems: 'center', gap: 6,
    fontFamily: "'JetBrains Mono', monospace", letterSpacing: '0.04em', textTransform: 'uppercase',
  },
  mobileRow: { paddingBottom: 14 },
  mobileMenuBtn: {
    display: 'inline-flex', alignItems: 'center', gap: 8,
    background: 'transparent', border: '1px solid rgba(42,26,7,.25)',
    padding: '9px 16px', minHeight: 44, cursor: 'pointer',
    fontFamily: "'JetBrains Mono', monospace", fontSize: 12,
    letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-900)',
  },
  mobilePanel: {
    display: 'flex', flexDirection: 'column',
    marginTop: 10, border: '1px solid rgba(42,26,7,.15)',
    background: '#fff', boxShadow: '4px 4px 0 0 var(--amber-500)',
  },
  mobileLink: {
    padding: '14px 16px', fontSize: 15, color: 'var(--ink-900)',
    textDecoration: 'none', borderTop: '1px solid rgba(42,26,7,.08)',
  },
  mobileSubToggle: {
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    width: '100%', background: 'transparent', border: 'none', cursor: 'pointer',
    padding: '14px 16px', fontSize: 15, fontFamily: 'inherit', color: 'var(--ink-900)',
    textAlign: 'left',
  },
  mobileSubPanel: {
    display: 'flex', flexDirection: 'column',
    background: 'var(--paper-200)', borderTop: '1px solid rgba(42,26,7,.08)',
  },
  mobileSubLink: {
    padding: '12px 16px 12px 28px', fontSize: 14, color: 'var(--ink-900)', textDecoration: 'none',
  },
};

const HOME_LINK = { id: 'top', label: 'Accueil' };

const NAV_LINKS = [
  { id: 'preuves', label: 'Résultats' },
  { id: 'methode', label: 'Méthode' },
  { id: 'studio-digital', label: 'Studio Digital' },
  { id: 'faq', label: 'FAQ' },
];

const OFFER_SUBLINKS = [
  { id: 'generateur', label: 'Générateur de propositions' },
  { id: 'support', label: 'Agent support 24/7' },
  { id: 'automatisation', label: 'Automatisation back-office' },
];

// Sous-menu « Offres » : s'ouvre au survol (desktop) ET au clic (clavier/
// tactile) ; un léger délai à la fermeture laisse le temps de traverser
// l'espace entre le bouton et le panneau en diagonale. Ferme sur Échap ou
// clic à l'extérieur.
const OffresDropdown = ({ root, activeSection }) => {
  const [open, setOpen] = React.useState(false);
  const wrapRef = React.useRef(null);
  const closeTimer = React.useRef(null);

  const cancelClose = () => {
    if (closeTimer.current) { clearTimeout(closeTimer.current); closeTimer.current = null; }
  };
  const openNow = () => { cancelClose(); setOpen(true); };
  const scheduleClose = () => {
    cancelClose();
    closeTimer.current = setTimeout(() => setOpen(false), 200);
  };

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

  React.useEffect(() => () => cancelClose(), []);

  return (
    <div
      ref={wrapRef}
      style={navStyles.dropdownWrap}
      onMouseEnter={openNow}
      onMouseLeave={scheduleClose}
    >
      <button
        type="button"
        style={navStyles.dropdownTrigger}
        className={'b2a-link' + (activeSection === 'offres' ? ' b2a-link-active' : '')}
        aria-haspopup="true"
        aria-expanded={open}
        onClick={() => setOpen((o) => !o)}
        onFocus={openNow}
      >
        Offres
        <Icon
          name="chevron-down"
          size={14}
          style={{ ...navStyles.dropdownChevron, transform: open ? 'rotate(180deg)' : 'none' }}
        />
      </button>
      {open && (
        <div style={navStyles.dropdownPanel} role="menu">
          {OFFER_SUBLINKS.map((o) => (
            <a
              key={o.id}
              href={`${root}offres/${o.id}.html`}
              role="menuitem"
              className="b2a-dropdown-item"
              onClick={() => setOpen(false)}
            >
              {o.label}
            </a>
          ))}
          <a
            href={root ? `${root}index.html#offres` : '#offres'}
            role="menuitem"
            style={navStyles.dropdownAll}
            onClick={() => setOpen(false)}
          >
            Voir toutes les offres <Icon name="arrow-right" size={12} />
          </a>
        </div>
      )}
    </div>
  );
};

// Menu mobile (< 960px) : bouton « Menu » à gauche, sous le logo, sur sa
// propre ligne (le bouton lui-même est masqué en desktop via la classe CSS
// .b2a-mobile-row). Déroule les liens de la nav + un sous-menu « Offres »
// repliable. Ferme sur Échap, clic à l'extérieur, sélection d'un lien, ou
// redimensionnement au-dessus du point de rupture.
const MobileMenu = ({ root, activeSection }) => {
  const [open, setOpen] = React.useState(false);
  const [offresOpen, setOffresOpen] = React.useState(false);
  const wrapRef = React.useRef(null);

  const closeAll = () => { setOpen(false); setOffresOpen(false); };

  React.useEffect(() => {
    if (!open) return;
    const onDocClick = (e) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) closeAll();
    };
    const onKey = (e) => { if (e.key === 'Escape') closeAll(); };
    const onResize = () => { if (window.innerWidth > 960) closeAll(); };
    document.addEventListener('mousedown', onDocClick);
    document.addEventListener('keydown', onKey);
    window.addEventListener('resize', onResize);
    return () => {
      document.removeEventListener('mousedown', onDocClick);
      document.removeEventListener('keydown', onKey);
      window.removeEventListener('resize', onResize);
    };
  }, [open]);

  return (
    <div ref={wrapRef} className="b2a-mobile-row" style={navStyles.mobileRow}>
      <button
        type="button"
        style={navStyles.mobileMenuBtn}
        aria-haspopup="true"
        aria-expanded={open}
        onClick={() => setOpen((o) => !o)}
      >
        <Icon name={open ? 'x' : 'menu'} size={16} />
        Menu
      </button>
      {open && (
        <nav style={navStyles.mobilePanel} aria-label="Navigation mobile">
          <a
            href={root ? `${root}index.html#${HOME_LINK.id}` : `#${HOME_LINK.id}`}
            style={navStyles.mobileLink}
            aria-current={activeSection === HOME_LINK.id ? 'page' : undefined}
            onClick={closeAll}
          >
            {HOME_LINK.label}
          </a>
          <button
            type="button"
            style={navStyles.mobileSubToggle}
            aria-haspopup="true"
            aria-expanded={offresOpen}
            onClick={() => setOffresOpen((o) => !o)}
          >
            Offres
            <Icon
              name="chevron-down"
              size={14}
              style={{ transform: offresOpen ? 'rotate(180deg)' : 'none', transition: 'transform 160ms var(--ease)' }}
            />
          </button>
          {offresOpen && (
            <div style={navStyles.mobileSubPanel}>
              {OFFER_SUBLINKS.map((o) => (
                <a
                  key={o.id}
                  href={`${root}offres/${o.id}.html`}
                  style={navStyles.mobileSubLink}
                  onClick={closeAll}
                >
                  {o.label}
                </a>
              ))}
              <a
                href={root ? `${root}index.html#offres` : '#offres'}
                style={navStyles.mobileSubLink}
                onClick={closeAll}
              >
                Voir toutes les offres
              </a>
            </div>
          )}
          {NAV_LINKS.map((l) => (
            <a
              key={l.id}
              href={root ? `${root}index.html#${l.id}` : `#${l.id}`}
              style={navStyles.mobileLink}
              aria-current={activeSection === l.id ? 'page' : undefined}
              onClick={closeAll}
            >
              {l.label}
            </a>
          ))}
        </nav>
      )}
    </div>
  );
};

// `root` : préfixe relatif pour atteindre 09_site-web/ depuis la page
// courante. '' sur index.html (comportement historique inchangé),
// '../' depuis une page satellite (ex. offres/generateur.html).
const Nav = ({ onBookCall, activeSection, root = '' }) => (
  <header style={navStyles.outer}>
    <div className="b2a-container" style={navStyles.inner}>
      <a
        href={root ? `${root}index.html#top` : '#top'}
        aria-label="TheB2ATeK — Accueil"
        style={{ backgroundImage: 'none' }}
      >
        <img
          src={`${root}08_assets-marque/design-system/assets/logo-2026.png`}
          alt="TheB2ATeK"
          style={navStyles.logo}
        />
      </a>
      <nav style={navStyles.links} className="b2a-nav-links" aria-label="Navigation principale">
        <a
          href={root ? `${root}index.html#${HOME_LINK.id}` : `#${HOME_LINK.id}`}
          className={'b2a-link' + (activeSection === HOME_LINK.id ? ' b2a-link-active' : '')}
          aria-current={activeSection === HOME_LINK.id ? 'page' : undefined}
        >
          {HOME_LINK.label}
        </a>
        <OffresDropdown root={root} activeSection={activeSection} />
        {NAV_LINKS.map((l) => (
          <a
            key={l.id}
            href={root ? `${root}index.html#${l.id}` : `#${l.id}`}
            className={'b2a-link' + (activeSection === l.id ? ' b2a-link-active' : '')}
            aria-current={activeSection === l.id ? 'page' : undefined}
          >
            {l.label}
          </a>
        ))}
      </nav>
      <div style={navStyles.right}>
        <a
          href={`${root}en/`}
          style={{
            fontFamily: "'JetBrains Mono', monospace",
            fontSize: 12,
            letterSpacing: '0.1em',
            color: 'var(--mist-700)',
            border: '1px solid rgba(42,26,7,.20)',
            padding: '5px 10px',
            textDecoration: 'none',
            display: 'inline-flex',
            alignItems: 'center',
            gap: 5,
          }}
          aria-label="Switch to English"
        >
          EN
        </a>
        <button className="b2a-btn b2a-btn-primary b2a-btn-sm" onClick={onBookCall}>
          Réserver un appel
        </button>
      </div>
    </div>
    <div className="b2a-container">
      <MobileMenu root={root} activeSection={activeSection} />
    </div>
  </header>
);

window.Nav = Nav;
