// Header - sticky transparent → charbon au scroll, 5 pages produit
// + 3 dropdowns (Entreprise / Aide / Légal), burger sous 1024px.
// Conserve : .ktk-header.is-scrolled, .ktk-nav-link, .wordmark, classes
// utilisées par aide-doc.css pour le contraste auto sur fond crème.

const Header = ({ active, basePath = '' }) => {
  const bp = basePath || '';
  const ref = React.useRef(null);

  // --- état ---
  const [openMenu, setOpenMenu] = React.useState(null);      // 'entreprise' | 'aide' | 'legal' | null
  const [openedByKey, setOpenedByKey] = React.useState(false);
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const [mobileSection, setMobileSection] = React.useState(null);
  const closeTimer = React.useRef(null);
  const itemRefs = React.useRef({});                          // par menu, liste de refs
  const burgerRef = React.useRef(null);
  const sheetRef = React.useRef(null);
  const prevMobileOpen = React.useRef(false);

  // --- scroll trigger (inchangé) ---
  React.useEffect(() => {
    const h = ref.current;
    if (!h) return;
    const onScroll = () => {
      if (window.scrollY > 50) h.classList.add('is-scrolled');
      else h.classList.remove('is-scrolled');
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // --- Escape ferme tout ---
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') {
        setOpenMenu(null);
        setOpenedByKey(false);
        setMobileOpen(false);
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  // --- verrou scroll quand burger ouvert ---
  React.useEffect(() => {
    document.body.style.overflow = mobileOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [mobileOpen]);

  // --- gestion du focus de la feuille mobile (entrée, piège, retour au burger) ---
  React.useEffect(() => {
    const sheet = sheetRef.current;
    if (mobileOpen) {
      const items = sheet ? sheet.querySelectorAll('a[href], button') : [];
      if (items[0]) items[0].focus();
      const onKey = (e) => {
        if (e.key !== 'Tab' || !items.length) return;
        const first = items[0], last = items[items.length - 1];
        if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
        else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
      };
      sheet && sheet.addEventListener('keydown', onKey);
      prevMobileOpen.current = true;
      return () => sheet && sheet.removeEventListener('keydown', onKey);
    } else if (prevMobileOpen.current) {
      prevMobileOpen.current = false;
      if (burgerRef.current) burgerRef.current.focus();
    }
  }, [mobileOpen]);

  const openWith = (k) => {
    clearTimeout(closeTimer.current);
    setOpenMenu(k);
  };
  const closeSoon = () => {
    clearTimeout(closeTimer.current);
    closeTimer.current = setTimeout(() => {
      setOpenMenu(null);
      setOpenedByKey(false);
    }, 150);
  };

  // --- focus 1er item quand ouvert au clavier ---
  React.useEffect(() => {
    if (openMenu && openedByKey) {
      const list = itemRefs.current[openMenu] || [];
      if (list[0]) list[0].focus();
    }
  }, [openMenu, openedByKey]);

  // --- nav clavier ↑/↓ dans le menu ouvert ---
  const onItemKey = (e, menuKey, idx) => {
    const list = itemRefs.current[menuKey] || [];
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      const next = list[(idx + 1) % list.length];
      if (next) next.focus();
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      const prev = list[(idx - 1 + list.length) % list.length];
      if (prev) prev.focus();
    } else if (e.key === 'Tab') {
      setOpenMenu(null);
      setOpenedByKey(false);
    }
  };

  // --- sélecteur de langue (FR ↔ EN) ---
  // LOCALE vaut 'fr' ici ; la copie traduite /proto/en/src/Header.jsx met 'en'.
  // Le cookie NEXT_LOCALE est lu par src/middleware.ts pour mémoriser le choix
  // explicite (sinon détection via Accept-Language).
  const LOCALE = 'fr';
  const switchLocale = (target) => {
    if (target === LOCALE) return;
    document.cookie =
      'NEXT_LOCALE=' + target + ';path=/;max-age=31536000;samesite=lax';
    const p = window.location.pathname;
    const frPath = p === '/en' ? '/' : (p.startsWith('/en/') ? p.slice(3) : p);
    window.location.assign(
      target === 'en' ? (frPath === '/' ? '/en' : '/en' + frPath) : frPath
    );
  };
  const LangSwitch = ({ compact }) => (
    <div className="ktk-lang-switch" role="group" aria-label="Choix de langue"
         style={compact ? { alignSelf: 'flex-start' } : null}>
      {['fr', 'en'].map(l => (
        <button key={l} type="button" lang={l}
                className={LOCALE === l ? 'is-active' : ''}
                aria-pressed={LOCALE === l}
                onClick={() => switchLocale(l)}>
          {l.toUpperCase()}
        </button>
      ))}
    </div>
  );

  // --- liens (clean Next.js URLs; bp prefix kept for potential standalone use) ---
  const productLinks = [
    { href: '/larene',          label: "L'Arène",          key: 'arene' },
    { href: '/communaute',      label: 'Communauté',       key: 'communaute' },
    { href: '/portefeuille',    label: 'Portefeuille',     key: 'portefeuille' },
    { href: '/securite',        label: 'Sécurité',         key: 'securite' },
    { href: '/mode-prediction', label: 'Mode Prédiction',  key: 'mode-prediction' },
  ];
  const groups = [
    { key: 'entreprise', label: 'Entreprise', align: 'left', items: [
      { l: 'À propos',     h: '/a-propos' },
      { l: 'Carrière',     h: '/carriere' },
      { l: 'Blog',         h: '/blog' },
      { l: 'Presse',       h: '/presse' },
      { l: 'Bêta privée',  h: '/beta-privee' },
    ]},
    { key: 'aide', label: 'Aide', align: 'left', items: [
      { l: 'FAQ',             h: '/faq' },
      { l: "Centre d'aide",   h: '/centre-aide' },
      { l: 'Nous contacter',  h: '/contact' },
      { l: 'Statut système',  h: '/statut' },
    ]},
    { key: 'legal', label: 'Légal', align: 'right', items: [
      { l: 'CGU',              h: '/legal/cgu' },
      { l: 'Confidentialité',  h: '/legal/confidentialite' },
      { l: 'Cookies',          h: '/legal/cookies' },
      { l: 'Mentions légales', h: '/legal/mentions' },
      { l: 'Jeu responsable',  h: '/legal/jeu-responsable' },
    ]},
  ];

  return (
    <>
    <header ref={ref} className="ktk-header" style={{
      position: 'sticky', top: 0, zIndex: 50,
      background: 'transparent',
      backdropFilter: 'blur(0px)',
      WebkitBackdropFilter: 'blur(0px)',
      borderBottom: '1px solid transparent',
    }}>
      <style>{`
        .ktk-header.is-scrolled {
          background: rgba(10,10,11,0.85) !important;
          backdrop-filter: blur(16px) !important;
          -webkit-backdrop-filter: blur(16px) !important;
          border-bottom-color: var(--hairline-on-dark) !important;
        }
        .ktk-nav-link { position: relative; }
        .ktk-nav-link::after {
          content: ""; position: absolute; left: 0; right: 0; bottom: -6px;
          height: 1px; background: var(--signature);
          transform: scaleX(0); transform-origin: left;
          transition: transform 220ms cubic-bezier(0.2,0.8,0.2,1);
        }
        .ktk-nav-link:hover::after,
        .ktk-nav-link.is-active::after { transform: scaleX(1); }
        .ktk-nav-link.is-active { color: var(--fg-on-dark) !important; }

        /* Bouton parent de dropdown - même rendu qu'un nav link */
        .ktk-drop-btn {
          background: transparent; border: 0; padding: 0; margin: 0;
          font: inherit; color: inherit; cursor: pointer;
          display: inline-flex; align-items: center; gap: 4px;
          color: var(--fg-on-dark-muted);
          font-family: var(--font-body); font-weight: 500;
          font-size: 14px; line-height: 1;
        }
        .ktk-drop-btn .caret {
          font-family: var(--font-mono);
          font-size: 10px;
          line-height: 1;
          transition: transform 200ms ease-out;
          display: inline-block;
        }
        .ktk-drop-btn[aria-expanded="true"] .caret { transform: rotate(180deg); }

        /* Panel dropdown - toujours dark, indépendamment du fond du header */
        .ktk-dropdown-panel {
          position: absolute; top: 100%;
          padding-top: 8px; /* bridge invisible - pas de "trou" */
          z-index: 60;
          opacity: 0; transform: translateY(-4px);
          pointer-events: none;
          transition: opacity 150ms ease-in, transform 150ms ease-in;
        }
        .ktk-dropdown-panel.is-open {
          opacity: 1; transform: translateY(0);
          pointer-events: auto;
          transition: opacity 200ms ease-out, transform 200ms ease-out;
        }
        .ktk-dropdown-panel.align-left  { left: 0; }
        .ktk-dropdown-panel.align-right { right: 0; }
        .ktk-dropdown-card {
          width: 240px;
          background: #141416;
          border: 1px solid rgba(244,239,230,0.10);
          border-radius: 16px;
          padding: 8px;
          box-shadow: 0 8px 32px rgba(0,0,0,0.24);
        }
        .ktk-dropdown-item {
          display: flex; align-items: center; justify-content: space-between;
          padding: 12px 16px; border-radius: 8px;
          font-family: var(--font-body); font-weight: 500; font-size: 14px;
          color: rgba(244,239,230,0.9);
          text-decoration: none;
          margin-bottom: 2px;
          transition: background 150ms ease-out, color 150ms ease-out;
          overflow: hidden;
        }
        .ktk-dropdown-item:last-child { margin-bottom: 0; }
        .ktk-dropdown-item .arrow {
          font-family: var(--font-mono);
          font-size: 13px;
          opacity: 0;
          transform: translateX(-6px);
          transition: opacity 200ms ease-out, transform 200ms ease-out;
        }
        .ktk-dropdown-item:hover,
        .ktk-dropdown-item:focus-visible {
          background: rgba(244,239,230,0.06);
          color: rgba(244,239,230,1);
          outline: none;
        }
        .ktk-dropdown-item:hover .arrow,
        .ktk-dropdown-item:focus-visible .arrow {
          opacity: 0.7;
          transform: translateX(0);
        }

        /* Override pour le cas "fond crème" géré par aide-doc.css :
           le panel reste lisible (charbon-doux + texte crème).
           aide-doc.css cible "body.aide-body .ktk-header:not(.is-scrolled) a"
           (spécificité 0,0,3,2) - on égale la spécificité avec "a.ktk-dropdown-item"
           et on gagne par ordre (style inline du Header rendu après le link). */
        body.aide-body .ktk-header a.ktk-dropdown-item,
        .ktk-header a.ktk-dropdown-item {
          color: rgba(244,239,230,0.9) !important;
        }
        body.aide-body .ktk-header a.ktk-dropdown-item:hover,
        body.aide-body .ktk-header a.ktk-dropdown-item:focus-visible,
        .ktk-header a.ktk-dropdown-item:hover,
        .ktk-header a.ktk-dropdown-item:focus-visible {
          color: rgba(244,239,230,1) !important;
        }
        /* Sheet mobile - overlay charbon plein écran rendu HORS du header
           (voir le render plus bas) pour que son position:fixed échappe au
           bloc conteneur créé par le backdrop-filter du header. Il garde une
           palette sombre sur toutes les pages, y compris les pages d'aide
           crème, donc on l'affirme explicitement. */
        .ktk-mobile-sheet a.ktk-mobile-flat-link {
          color: var(--fg-on-dark) !important;
        }
        .ktk-mobile-sheet a.ktk-mobile-flat-link.is-active {
          color: var(--signature) !important;
        }
        .ktk-mobile-sheet .ktk-mobile-acc-panel a {
          color: var(--fg-on-dark-muted) !important;
        }

        /* Espacement nav : 32px par défaut, 20px en intermédiaire */
        .ktk-nav-row { gap: 32px; }
        @media (max-width: 1280px) { .ktk-nav-row { gap: 20px; } }

        /* Burger / mobile (≤1180px : la nav FR plus longue passe au menu avant de déborder) */
        .ktk-burger { display: none; }
        @media (max-width: 1180px) {
          .ktk-nav-row { display: none !important; }
          .ktk-header .ktk-cta-secondary { display: none !important; }
          .ktk-burger { display: inline-flex; }
          /* gouttières resserrées + CTA compact pour tenir sur une ligne (≥360px) */
          .ktk-header-bar { padding-left: 14px !important; padding-right: 14px !important; }
          .ktk-cta-primary { padding: 0 12px !important; font-size: 12px !important; }
        }
        .ktk-burger {
          width: 44px; height: 44px;
          align-items: center; justify-content: center;
          background: transparent; border: 0; cursor: pointer;
          color: var(--fg-on-dark);
          margin-left: 8px;
        }
        .ktk-burger svg { width: 22px; height: 22px; }

        /* Mobile sheet */
        .ktk-mobile-sheet {
          position: fixed; inset: 0;
          background: var(--charbon-profond);
          z-index: 100;
          display: flex; flex-direction: column;
          padding: 20px 24px 32px;
          overflow-y: auto;
          transform: translateY(-8px);
          opacity: 0; pointer-events: none; visibility: hidden;
          transition: opacity 220ms ease-out, transform 220ms ease-out, visibility 0s linear 220ms;
        }
        .ktk-mobile-sheet.is-open {
          opacity: 1; transform: translateY(0); pointer-events: auto; visibility: visible;
          transition: opacity 220ms ease-out, transform 220ms ease-out, visibility 0s;
        }
        .ktk-mobile-sheet-head {
          display: flex; align-items: center; justify-content: space-between;
          margin-bottom: 32px;
        }
        .ktk-mobile-flat a {
          display: block;
          font-family: var(--font-display);
          font-weight: 700;
          font-size: 28px;
          letter-spacing: -0.02em;
          color: var(--fg-on-dark);
          text-decoration: none;
          padding: 10px 0;
        }
        .ktk-mobile-flat a.is-active { color: var(--signature); }
        .ktk-mobile-divider {
          height: 1px; background: var(--hairline-on-dark);
          margin: 24px 0;
        }
        .ktk-mobile-acc-btn {
          width: 100%;
          background: transparent; border: 0; padding: 14px 0;
          display: flex; align-items: center; justify-content: space-between;
          font-family: var(--font-body); font-weight: 500;
          font-size: 16px;
          color: var(--fg-on-dark);
          cursor: pointer;
          border-bottom: 1px solid var(--hairline-on-dark);
        }
        .ktk-mobile-acc-btn .caret {
          font-family: var(--font-mono); font-size: 12px;
          transition: transform 250ms ease-out;
        }
        .ktk-mobile-acc-btn[aria-expanded="true"] .caret { transform: rotate(180deg); }
        .ktk-mobile-acc-panel {
          overflow: hidden;
          max-height: 0;
          transition: max-height 250ms ease-out;
        }
        .ktk-mobile-acc-panel.is-open { max-height: 360px; }
        .ktk-mobile-acc-panel a {
          display: block;
          padding: 10px 0 10px 24px;
          font-family: var(--font-body); font-size: 15px;
          color: var(--fg-on-dark-muted);
          text-decoration: none;
        }
        .ktk-mobile-acc-panel a:first-child { padding-top: 14px; }
        .ktk-mobile-acc-panel a:last-child { padding-bottom: 18px; }
        .ktk-mobile-cta {
          margin-top: auto;
          padding-top: 24px;
          display: flex; flex-direction: column; gap: 12px;
        }

        /* Sélecteur de langue FR/EN */
        .ktk-lang-switch {
          display: inline-flex; align-items: center;
          border: 1px solid var(--hairline-on-dark);
          border-radius: 999px; padding: 2px;
        }
        .ktk-lang-switch button {
          background: transparent; border: 0; cursor: pointer;
          font-family: var(--font-mono); font-size: 11px;
          letter-spacing: 0.08em; line-height: 1;
          color: var(--fg-on-dark-muted);
          padding: 6px 10px; border-radius: 999px;
          transition: background 150ms ease-out, color 150ms ease-out;
        }
        .ktk-lang-switch button.is-active {
          background: rgba(244,239,230,0.12);
          color: var(--fg-on-dark);
        }
        .ktk-lang-switch button:not(.is-active):hover {
          color: var(--fg-on-dark);
        }
        /* Contraste sur fond crème (pages aide non scrollées) */
        body.aide-body .ktk-header:not(.is-scrolled) .ktk-lang-switch,
        body.aide-cat-body .ktk-header:not(.is-scrolled) .ktk-lang-switch {
          border-color: rgba(10,10,11,0.18);
        }
        body.aide-body .ktk-header:not(.is-scrolled) .ktk-lang-switch button,
        body.aide-cat-body .ktk-header:not(.is-scrolled) .ktk-lang-switch button {
          color: rgba(10, 10, 11, 0.65);
        }
        body.aide-body .ktk-header:not(.is-scrolled) .ktk-lang-switch button.is-active,
        body.aide-cat-body .ktk-header:not(.is-scrolled) .ktk-lang-switch button.is-active {
          background: rgba(10,10,11,0.08);
          color: var(--charbon-profond);
        }
        @media (max-width: 1023px) {
          .ktk-header > div > div > .ktk-lang-switch { display: none; }
        }
      `}</style>

      <div className="ktk-header-bar" style={{
        maxWidth: 1280, margin: '0 auto',
        padding: '18px 32px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        gap: 24,
      }}>
        <a href="/" style={{ textDecoration: 'none', color: 'var(--fg-on-dark)' }}>
          <span className="wordmark" style={{ fontSize: 22 }}>
            <span className="k-initial">K</span>tkarena
          </span>
        </a>

        <nav className="ktk-nav-row" style={{
          display: 'flex', alignItems: 'center', fontSize: 14,
        }}>
          {productLinks.map(l => (
            <a key={l.key} href={l.href}
               className={'ktk-nav-link' + (active === l.key ? ' is-active' : '')}
               style={navLink}>{l.label}</a>
          ))}

          {groups.map(g => (
            <div key={g.key}
                 style={{ position: 'relative' }}
                 onMouseEnter={() => openWith(g.key)}
                 onMouseLeave={closeSoon}>
              <button
                type="button"
                className={'ktk-nav-link ktk-drop-btn'}
                aria-haspopup="menu"
                aria-expanded={openMenu === g.key}
                onClick={(e) => {
                  e.preventDefault();
                  if (openMenu === g.key) { setOpenMenu(null); setOpenedByKey(false); }
                  else { setOpenMenu(g.key); setOpenedByKey(true); }
                }}
                onKeyDown={(e) => {
                  if (e.key === 'ArrowDown' || e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    setOpenMenu(g.key);
                    setOpenedByKey(true);
                  }
                }}
              >
                <span>{g.label}</span>
                <span className="caret" aria-hidden="true">▾</span>
              </button>

              <div
                role="menu"
                aria-label={g.label}
                className={
                  'ktk-dropdown-panel align-' + g.align +
                  (openMenu === g.key ? ' is-open' : '')
                }
              >
                <div className="ktk-dropdown-card">
                  {g.items.map((it, idx) => (
                    <a
                      key={it.l}
                      ref={(el) => {
                        if (!itemRefs.current[g.key]) itemRefs.current[g.key] = [];
                        itemRefs.current[g.key][idx] = el;
                      }}
                      href={it.h}
                      role="menuitem"
                      className="ktk-dropdown-item"
                      onKeyDown={(e) => onItemKey(e, g.key, idx)}
                    >
                      <span>{it.l}</span>
                      <span className="arrow" aria-hidden="true">→</span>
                    </a>
                  ))}
                </div>
              </div>
            </div>
          ))}
        </nav>

        <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
          <LangSwitch />
          <a href="#" className="ktk-nav-link ktk-cta-secondary" style={{ ...navLink, fontSize: 14 }}>Se connecter</a>
          <a href="#" className="btn btn-primary ktk-cta-primary" style={{ height: 40, padding: '0 18px', fontSize: 14, whiteSpace: 'nowrap' }}>
            Entrer dans l'arène
          </a>
          <button
            ref={burgerRef}
            type="button"
            className="ktk-burger"
            aria-label="Ouvrir le menu"
            aria-expanded={mobileOpen}
            onClick={() => setMobileOpen(true)}
          >
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round">
              <path d="M4 7h16" />
              <path d="M4 12h16" />
              <path d="M4 17h16" />
            </svg>
          </button>
        </div>
      </div>
    </header>

      {/* Sheet mobile - rendu HORS du <header> pour que son position:fixed se
          résolve par rapport au viewport, et non au bloc conteneur créé par le
          backdrop-filter du header */}
      <div
        ref={sheetRef}
        role="dialog"
        aria-modal="true"
        aria-label="Menu"
        className={'ktk-mobile-sheet' + (mobileOpen ? ' is-open' : '')}
        aria-hidden={!mobileOpen}
      >
        <div className="ktk-mobile-sheet-head">
          <a href="/" style={{ textDecoration: 'none', color: 'var(--fg-on-dark)' }}>
            <span className="wordmark" style={{ fontSize: 22 }}>
              <span className="k-initial">K</span>tkarena
            </span>
          </a>
          <button
            type="button"
            aria-label="Fermer le menu"
            onClick={() => setMobileOpen(false)}
            style={{
              width: 40, height: 40, background: 'transparent', border: 0,
              color: 'var(--fg-on-dark)', cursor: 'pointer',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            }}
          >
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round">
              <path d="M6 6l12 12" />
              <path d="M18 6L6 18" />
            </svg>
          </button>
        </div>

        <div className="ktk-mobile-flat">
          {productLinks.map(l => (
            <a key={l.key} href={l.href}
               className={'ktk-mobile-flat-link' + (active === l.key ? ' is-active' : '')}>{l.label}</a>
          ))}
        </div>

        <div className="ktk-mobile-divider" />

        {groups.map(g => {
          const open = mobileSection === g.key;
          return (
            <div key={g.key}>
              <button
                type="button"
                className="ktk-mobile-acc-btn"
                aria-expanded={open}
                onClick={() => setMobileSection(open ? null : g.key)}
              >
                <span>{g.label}</span>
                <span className="caret" aria-hidden="true">▾</span>
              </button>
              <div className={'ktk-mobile-acc-panel' + (open ? ' is-open' : '')}>
                {g.items.map(it => (
                  <a key={it.l} href={it.h}>{it.l}</a>
                ))}
              </div>
            </div>
          );
        })}

        <div className="ktk-mobile-cta">
          <LangSwitch compact />
          <a href="#" className="btn btn-secondary" style={{ height: 48, fontSize: 15 }}>Se connecter</a>
          <a href="#" className="btn btn-primary" style={{ height: 48, fontSize: 15 }}>
            Entrer dans l'arène
          </a>
        </div>
      </div>
    </>
  );
};

const navLink = {
  color: 'var(--fg-on-dark-muted)', textDecoration: 'none',
  fontFamily: 'var(--font-body)', fontWeight: 500,
  whiteSpace: 'nowrap',
};
window.Header = Header;
