/* global React */
/* Header PARTAGÉ du portail revendeur French Kits (barre pro + marque + nav + compte/panier + burger mobile).
   Self-contained : lit window.NAV_TABS / window.CLIENT / window.EXTRANET_CONFIG / window.PORTAIL_CONFIG / window.EcUI.
   Props: orderUnits (badge panier). Définit un EcHeader global réutilisable. */
function EcHeader({ orderUnits }) {
  const cfg = window.EXTRANET_CONFIG || {};
  const pc = window.PORTAIL_CONFIG || {};
  const base = cfg.base_url || '';
  const client = window.CLIENT;
  const isLogged = !!(client && client.nom);
  const navTabs = window.NAV_TABS || [];

  // Badge panier : compteur serveur, resynchronisé sur l'événement 'ec-cart-changed' (cohérent sur toutes les pages)
  const [units, setUnits] = React.useState(orderUnits || 0);
  React.useEffect(() => {
    if (!isLogged) { setUnits(0); return; }
    const load = () => fetch(base + '/panier', { credentials: 'same-origin' }).then(r => r.json()).then(d => setUnits(parseInt(d.nb_articles, 10) || 0)).catch(() => {});
    load();
    window.addEventListener('ec-cart-changed', load);
    return () => window.removeEventListener('ec-cart-changed', load);
  }, [isLogged, base]);

  const T = (window.EcUI && window.EcUI.T) || {};
  const INK = T.ink || 'oklch(0.255 0.016 48)';
  const PRIMARY = T.primary || 'oklch(0.62 0.14 40)';
  const PROBAR = T.probar || 'oklch(0.5 0.12 38)';
  const CORAL = T.coral || 'oklch(0.575 0.125 42)';
  const CREAM = T.cream || 'oklch(0.945 0.016 82)';
  const GREY = T.mute || 'oklch(0.55 0.012 65)';
  const ONBAR = T.onbar || 'oklch(0.95 0.03 65)';
  const SERIF = T.serif || "'Playfair Display',serif";

  const marque = pc.marque || 'French Kits';
  const accent = pc.marque_accent || 'Kits';
  const marquePrefix = accent && marque.indexOf(accent) === 0 ? '' : (marque.split(accent)[0] || '');
  const societe = pc.societe || 'Émotions Créatives';
  const badge = pc.badge || 'PORTAIL REVENDEUR';
  const logo = pc.logo || '';
  const baseline = pc.header_baseline || ('par ' + societe);
  const barreLabel = pc.barre_label || 'ESPACE REVENDEUR PROFESSIONNEL';
  const reassurances = (pc.reassurances && pc.reassurances.length) ? pc.reassurances : ['Tarifs HT réservés aux professionnels', 'Fabriqué en France 🇫🇷'];

  const [open, setOpen] = React.useState(false);    // menu compte
  const [menu, setMenu] = React.useState(false);     // menu burger mobile
  const [cartOpen, setCartOpen] = React.useState(false); // cart drawer
  React.useEffect(() => {
    if (!open) return;
    const h = (e) => { if (!e.target.closest('.ec-chip-wrap')) setOpen(false); };
    document.addEventListener('click', h);
    return () => document.removeEventListener('click', h);
  }, [open]);

  return (
    <React.Fragment>
      {/* ===== Barre utilitaire pro (terracotta) ===== */}
      <div style={{ background: PROBAR, color: ONBAR, fontFamily: T.sans || "'Hanken Grotesk',sans-serif" }}>
        <div className="ec-probar" style={{ maxWidth: 1240, margin: '0 auto', padding: '9px 32px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap', fontSize: 12 }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 9, fontWeight: 700, letterSpacing: '.16em' }}><span style={{ width: 7, height: 7, borderRadius: 999, background: ONBAR }}></span>{barreLabel}</span>
          <span className="ec-proextra" style={{ display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap', opacity: .92 }}>
            {reassurances.map((r, i) => (
              <React.Fragment key={i}>
                {i > 0 && <span style={{ opacity: .4 }}>·</span>}
                <span>{r}</span>
              </React.Fragment>
            ))}
          </span>
        </div>
      </div>

      {/* ===== Header sticky ===== */}
      <header style={{ position: 'sticky', top: 0, zIndex: 40, background: CREAM, borderBottom: '1px solid oklch(0.88 0.012 75)', fontFamily: T.sans || "'Hanken Grotesk',sans-serif" }}>
        <div className="ec-topbar-inner" style={{ maxWidth: 1240, margin: '0 auto', padding: '18px 32px', display: 'flex', alignItems: 'center', gap: 34 }}>
          {/* Marque : logo image (ou lockup texte si pas de logo) + baseline société */}
          <a href={cfg.home_url || (base + '/home')} style={{ display: 'flex', flexDirection: 'column', gap: 6, textDecoration: 'none' }}>
            {logo
              ? <img src={logo} alt={marque} style={{ height: 27, width: 'auto', display: 'block' }} />
              : <span style={{ fontFamily: SERIF, fontWeight: 600, fontSize: 25, letterSpacing: '-.01em', lineHeight: 1, color: INK }}>{marquePrefix}<span style={{ fontStyle: 'italic', color: CORAL }}>{accent}</span><span style={{ fontSize: 12, verticalAlign: 'super', color: GREY }}>®</span></span>}
            <span style={{ fontSize: 10, fontWeight: 600, letterSpacing: '.09em', color: GREY, textTransform: 'uppercase', paddingLeft: 1 }}>{baseline}</span>
          </a>

          {/* Nav (slide-in en mobile) */}
          <nav className={"ec-nav" + (menu ? " ec-nav-open" : "")} style={{ display: 'flex', alignItems: 'center', gap: 6, flex: 1, justifyContent: 'center' }}>
            <button className="ec-navclose" onClick={() => setMenu(false)} aria-label="Fermer" style={{ display: 'none', position: 'absolute', top: 16, right: 16, width: 40, height: 40, alignItems: 'center', justifyContent: 'center', background: 'transparent', border: 'none', fontSize: 30, lineHeight: 1, color: 'oklch(0.4 0.015 55)', cursor: 'pointer' }}>×</button>
            <div className="ec-menu-label">Menu principal</div>
            {navTabs.map((t, i) => t.active ? (
              <span key={i} style={{ fontSize: 14.5, fontWeight: 600, color: '#fff', background: PRIMARY, padding: '9px 18px', borderRadius: 999, textAlign: 'center', whiteSpace: 'nowrap' }}>{t.label}</span>
            ) : (
              <a key={i} href={t.url} onClick={() => setMenu(false)} style={{ fontSize: 14.5, fontWeight: 500, color: 'oklch(0.4 0.015 55)', padding: '9px 14px', textDecoration: 'none', textAlign: 'center', whiteSpace: 'nowrap' }}>{t.label}</a>
            ))}
            <div className="ec-menu-extra">
              <div className="ec-menu-label" style={{ marginTop: 16 }}>Mon espace</div>
              {isLogged ? (
                <React.Fragment>
                  <a className="ec-menu-link" href={base + '/mon-profil'}>Mon profil</a>
                  <a className="ec-menu-link" href={base + '/mes-adresses'}>Mes adresses</a>
                  <a className="ec-menu-link" href={cfg.mes_commandes_url || (base + '/mes-commandes')}>Mes commandes</a>
                  <a className="ec-menu-link" href={base + '/logout'} style={{ color: CORAL, fontWeight: 600 }}>Se déconnecter</a>
                </React.Fragment>
              ) : (
                <React.Fragment>
                  <a className="ec-menu-link" href={cfg.connexion_url || (base + '/connexion')} style={{ color: '#fff', background: PRIMARY, fontWeight: 600 }}>Se connecter</a>
                  <a className="ec-menu-link" href={cfg.connexion_url || (base + '/connexion')}>Devenir revendeur</a>
                </React.Fragment>
              )}
            </div>
          </nav>

          {/* Zone droite */}
          <div className="ec-actions" style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 14 }}>
            <button className="ec-burger" onClick={() => setMenu(m => !m)} aria-label="Menu" style={{ display: 'none', width: 46, height: 46, alignItems: 'center', justifyContent: 'center', background: 'transparent', border: '1.5px solid oklch(0.82 0.014 70)', borderRadius: 12, fontSize: 19, color: 'oklch(0.3 0.016 48)', cursor: 'pointer' }}>☰</button>
            {isLogged ? (
              <React.Fragment>
                <div className="ec-chip-wrap" style={{ position: 'relative' }}>
                  <button type="button" onClick={() => setOpen(o => !o)} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '7px 16px 7px 8px', border: '1px solid oklch(0.86 0.012 75)', borderRadius: 999, background: 'transparent', cursor: 'pointer' }}>
                    <span style={{ width: 30, height: 30, borderRadius: 999, background: 'oklch(0.93 0.02 80)', color: CORAL, display: 'grid', placeItems: 'center', fontFamily: SERIF, fontStyle: 'italic', fontWeight: 600, fontSize: 15 }}>{client.initiale || '?'}</span>
                    <span className="ec-chip-meta" style={{ lineHeight: 1.15, textAlign: 'left' }}>
                      <span style={{ display: 'block', fontSize: 13.5, fontWeight: 700, color: 'oklch(0.28 0.016 48)' }}>{client.nom}</span>
                      <span style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11.5, color: GREY }}><span style={{ width: 6, height: 6, borderRadius: 999, background: 'oklch(0.6 0.12 150)' }}></span>Compte revendeur actif</span>
                    </span>
                    <span style={{ color: GREY, fontSize: 15, paddingLeft: 4 }}>⌄</span>
                  </button>
                  {open && (
                    <div style={{ position: 'absolute', top: '112%', right: 0, minWidth: 200, background: '#fff', border: '1px solid oklch(0.88 0.012 75)', borderRadius: 12, boxShadow: '0 18px 40px -16px rgba(40,30,20,.25)', padding: 6, zIndex: 60 }}>
                      {[['Mon profil', base + '/mon-profil'], ['Mes adresses', base + '/mes-adresses'], ['Mes commandes', cfg.mes_commandes_url || (base + '/mes-commandes')]].map(([lbl, href], i) => (
                        <a key={i} href={href} style={{ display: 'block', padding: '9px 12px', fontSize: 13.5, color: 'oklch(0.3 0.016 48)', textDecoration: 'none', borderRadius: 8 }}>{lbl}</a>
                      ))}
                      <div style={{ height: 1, background: 'oklch(0.9 0.012 75)', margin: '6px 4px' }}></div>
                      <a href={base + '/logout'} style={{ display: 'block', padding: '9px 12px', fontSize: 13.5, color: CORAL, textDecoration: 'none', borderRadius: 8 }}>Se déconnecter</a>
                    </div>
                  )}
                </div>
                <button onClick={() => setCartOpen(true)} aria-label="Voir le panier" style={{ position: 'relative', width: 46, height: 46, borderRadius: 999, background: PRIMARY, color: '#fff', display: 'grid', placeItems: 'center', border: 'none', cursor: 'pointer' }}>
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="9" cy="21" r="1" /><circle cx="20" cy="21" r="1" /><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6" /></svg>
                  {units > 0 && <span style={{ position: 'absolute', top: -5, right: -5, minWidth: 20, height: 20, padding: '0 5px', borderRadius: 999, background: CORAL, color: '#fff', fontSize: 11, fontWeight: 700, display: 'grid', placeItems: 'center', border: '2px solid ' + CREAM }}>{units}</span>}
                </button>
              </React.Fragment>
            ) : (
              <a href={cfg.connexion_url || (base + '/connexion')} style={{ background: PRIMARY, color: '#fff', fontWeight: 600, fontSize: 14, padding: '12px 22px', borderRadius: 999, textDecoration: 'none' }}>Se connecter</a>
            )}
          </div>
        </div>
        {/* Backdrop menu mobile — DANS le header (même contexte d'empilement que le panneau de nav) */}
        <div className={"ec-backdrop" + (menu ? " ec-open" : "")} onClick={() => setMenu(false)}></div>
      </header>

      {/* Barre de chips raccourcis (sous le header) : New Printemps · New Été · Commander (sans Accueil) */}
      <div className="ec-chipsbar" style={{ background: CREAM, borderBottom: '1px solid oklch(0.88 0.012 75)', fontFamily: T.sans || "'Hanken Grotesk',sans-serif" }}>
        <div style={{ maxWidth: 1240, margin: '0 auto', padding: '10px 18px', display: 'flex', gap: 8, overflowX: 'auto' }}>
          {[{ slug: 'nouveautes-printemps', label: 'Printemps', neu: true }, { slug: 'nouveautes-ete', label: 'Été', neu: true }, { slug: 'commander', label: 'Commander', neu: false }].map((c) => {
            const t = navTabs.find(x => x.slug === c.slug);
            if (!t) return null;
            return (
              <a key={c.slug} href={t.url} style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0, fontSize: 13.5, fontWeight: 600, padding: '8px 14px', borderRadius: 999, textDecoration: 'none', whiteSpace: 'nowrap', color: t.active ? '#fff' : 'oklch(0.42 0.015 55)', background: t.active ? PRIMARY : 'oklch(0.965 0.012 84)', border: t.active ? 'none' : '1px solid oklch(0.88 0.012 75)' }}>
                {c.neu && <span style={{ fontSize: 9, fontWeight: 700, letterSpacing: '.05em', textTransform: 'uppercase', color: '#fff', background: '#e02424', padding: '2px 5px', borderRadius: 4 }}>New</span>}
                {c.label}
              </a>
            );
          })}
        </div>
      </div>

      {/* Cart drawer partagé */}
      {typeof EcCartDrawer !== 'undefined' && <EcCartDrawer open={cartOpen} onClose={() => setCartOpen(false)} />}
    </React.Fragment>
  );
}
