// Header with bilingual switch + nav + mobile hamburger
function Header({ lang, setLang, route, setRoute, openAI, openCallback, user, onLogout }) {
  const t = (ru, en) => (lang === 'ru' ? ru : en);
  const [open, setOpen] = React.useState(null);
  const [userMenuOpen, setUserMenuOpen] = React.useState(false);
  const [mobileOpen, setMobileOpen] = React.useState(false);

  const NAV = [
    { id: 'citizenship', label: t('Гражданство', 'Citizenship') },
    { id: 'residency',   label: t('ВНЖ',         'Residency') },
    { id: 'relocate',    label: t('Переезд',     'Relocation') },
    { id: 'invest',      label: t('Инвестиции',  'Investments') },
    { id: 'tools',       label: t('Инструменты', 'Tools') },
    { id: 'about',       label: t('Migronis',    'About') },
  ];

  const navigateTo = (id) => {
    if (id === 'citizenship') setRoute({ name: 'citizenship' });
    else if (id === 'residency') setRoute({ name: 'residency' });
    else if (id === 'relocate')  setRoute({ name: 'relocate' });
    else if (id === 'invest')    setRoute({ name: 'invest' });
    else if (id === 'tools')     setRoute({ name: 'home', scrollTo: 'tools' });
    else setRoute({ name: id });
    setMobileOpen(false);
  };

  // Initials for avatar
  const initials = user && user.name
    ? user.name.split(' ').map((s) => s[0]).slice(0, 2).join('').toUpperCase()
    : '';

  return (
    <header style={{
      position: 'sticky', top: 14, zIndex: 50,
      padding: '0 24px',
    }}>
      <div className="glass header-bar" style={{
        margin: '0 auto', maxWidth: 1400,
        display: 'grid', gridTemplateColumns: 'auto 1fr auto',
        alignItems: 'center', gap: 24,
        padding: '12px 18px 12px 22px',
      }}>
        {/* Logo – real Migronis wordmark, white on the dark header */}
        <a href="#" onClick={(e) => { e.preventDefault(); setRoute({ name: 'home' }); setMobileOpen(false); }}
           style={{ display: 'flex', alignItems: 'center', lineHeight: 1 }}>
          <window.MigronisLogo height={26} color="#FFFFFF" />
        </a>

        {/* Desktop nav */}
        <nav className="header-nav-desktop" style={{ display: 'flex', justifyContent: 'center', gap: 4 }}>
          {NAV.map((n) => (
            <button key={n.id}
              onClick={() => navigateTo(n.id)}
              onMouseEnter={() => setOpen(n.id)}
              onMouseLeave={() => setOpen(null)}
              className="tab"
              style={{
                background: 'transparent',
                color: '#FFFFFF',
                borderBottom: `2px solid ${open === n.id ? '#FFFFFF' : 'transparent'}`,
                marginBottom: -1,
                minWidth: 100,
                padding: '0 14px',
                textAlign: 'center', whiteSpace: 'nowrap',
                transition: 'border-color .15s, color .15s',
              }}
            >
              {n.label}
            </button>
          ))}
        </nav>

        {/* Right actions */}
        <div className="header-actions" style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          {/* Language switch – always visible */}
          <div style={{
            display: 'inline-flex',
            border: '1px solid rgba(255,255,255,0.22)',
          }}>
            {['ru', 'en'].map((l, i) => (
              <button key={l}
                onClick={() => setLang(l)}
                style={{
                  height: 32, padding: '0 12px',
                  fontSize: 11, letterSpacing: '0.12em',
                  textTransform: 'uppercase',
                  fontFamily: 'var(--f-mono)',
                  background: lang === l ? '#FFFFFF' : 'transparent',
                  color: lang === l ? '#191C1F' : '#FFFFFF',
                  borderLeft: i > 0 ? '1px solid rgba(255,255,255,0.22)' : 'none',
                  transition: 'background .15s, color .15s',
                }}>{l}</button>
            ))}
          </div>

          {/* AI button – hidden on mobile (lives inside the burger menu) */}
          <button className="btn btn-ghost btn-sm header-only-desktop" onClick={openAI} style={{ minWidth: 168 }}>
            <span style={{
              width: 6, height: 6, background: 'var(--accent)',
              boxShadow: '0 0 8px var(--accent)',
            }} />
            {t('AI-консультант', 'AI Advisor')}
          </button>

          <button className="btn btn-primary btn-sm header-only-desktop" onClick={openCallback} style={{ minWidth: 188 }}>
            {t('Бесплатная консультация', 'Free consultation')}
          </button>

          {/* User: sign-in OR avatar dropdown */}
          {!user && (
            <button onClick={() => setRoute({ name: 'auth' })}
              title={t('Личный кабинет', 'Client area')}
              className="header-only-desktop"
              style={{
                height: 32, width: 32,
                display: 'grid', placeItems: 'center',
                background: 'transparent', color: '#FFFFFF',
                border: '1px solid rgba(255,255,255,0.22)',
                cursor: 'pointer',
                transition: 'background .15s, border-color .15s',
              }}
              onMouseEnter={(e) => { e.currentTarget.style.background = 'rgba(255,255,255,0.08)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <circle cx="12" cy="8" r="4"/>
                <path d="M4 21c0-4.4 3.6-8 8-8s8 3.6 8 8"/>
              </svg>
            </button>
          )}
          {user && (
            <div className="header-only-desktop" style={{ position: 'relative' }}>
              <button onClick={() => setUserMenuOpen((v) => !v)}
                style={{
                  height: 32, minWidth: 32, padding: '0 6px',
                  background: 'var(--accent)', color: '#FFFFFF',
                  border: 0, cursor: 'pointer',
                  fontFamily: 'var(--f-sans)', fontSize: 11, fontWeight: 700, letterSpacing: '0.04em',
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                }}>
                {initials || 'U'}
              </button>
              {userMenuOpen && (
                <div onMouseLeave={() => setUserMenuOpen(false)}
                  style={{
                    position: 'absolute', top: 'calc(100% + 6px)', right: 0,
                    minWidth: 200,
                    background: 'var(--bg-elev)', border: '1px solid var(--border-strong)',
                    boxShadow: '0 12px 32px rgba(0,0,0,0.24)',
                    zIndex: 60,
                  }}>
                  <div style={{ padding: '12px 14px', borderBottom: '1px solid var(--border)' }}>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{user.name}</div>
                    <div style={{ fontSize: 11, color: 'var(--fg-muted)', marginTop: 2 }}>{user.email}</div>
                  </div>
                  <button onClick={() => { setUserMenuOpen(false); setRoute({ name: 'dashboard' }); }}
                          style={{ display: 'block', width: '100%', textAlign: 'left', padding: '10px 14px', background: 'transparent', border: 0, color: 'var(--fg)', fontSize: 13, cursor: 'pointer' }}>
                    {t('Личный кабинет', 'Dashboard')}
                  </button>
                  <button onClick={() => { setUserMenuOpen(false); onLogout(); }}
                          style={{ display: 'block', width: '100%', textAlign: 'left', padding: '10px 14px', background: 'transparent', border: 0, color: 'var(--fg-muted)', fontSize: 13, cursor: 'pointer', borderTop: '1px solid var(--border)' }}>
                    {t('Выйти', 'Sign out')}
                  </button>
                </div>
              )}
            </div>
          )}

          {/* Mobile hamburger */}
          <button onClick={() => setMobileOpen((v) => !v)}
                  aria-label={mobileOpen ? 'Close menu' : 'Open menu'}
                  className="header-burger"
                  style={{
                    height: 36, width: 36,
                    display: 'none', placeItems: 'center',
                    background: 'transparent', color: '#FFFFFF',
                    border: '1px solid rgba(255,255,255,0.22)',
                    cursor: 'pointer',
                  }}>
            {mobileOpen ? (
              <svg width="16" height="16" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2" fill="none">
                <path d="M6 6 L18 18 M6 18 L18 6"/>
              </svg>
            ) : (
              <svg width="16" height="16" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2" fill="none">
                <path d="M4 7 L20 7 M4 12 L20 12 M4 17 L20 17"/>
              </svg>
            )}
          </button>
        </div>
      </div>

      {/* Mobile drawer */}
      {mobileOpen && (
        <div className="header-mobile-drawer" style={{
          margin: '8px auto 0', maxWidth: 1400,
          background: 'rgba(25,28,31,0.96)',
          backdropFilter: 'blur(14px)', WebkitBackdropFilter: 'blur(14px)',
          border: '1px solid rgba(255,255,255,0.12)',
          padding: 18,
          display: 'flex', flexDirection: 'column', gap: 6,
        }}>
          {NAV.map((n) => (
            <button key={n.id} onClick={() => navigateTo(n.id)}
                    style={{
                      textAlign: 'left', height: 44, padding: '0 14px',
                      background: 'transparent', color: '#FFFFFF',
                      border: '1px solid rgba(255,255,255,0.08)',
                      fontSize: 14, fontFamily: 'var(--f-sans)',
                      cursor: 'pointer',
                    }}>
              {n.label}
            </button>
          ))}
          <div style={{ height: 1, background: 'rgba(255,255,255,0.12)', margin: '6px 0' }} />
          <button onClick={() => { setMobileOpen(false); openAI(); }}
                  className="btn btn-ghost btn-sm" style={{ width: '100%', justifyContent: 'flex-start', color: '#FFFFFF' }}>
            <span style={{ width: 6, height: 6, background: 'var(--accent)' }} />
            {t('AI-консультант', 'AI Advisor')}
          </button>
          <button onClick={() => { setMobileOpen(false); openCallback(); }}
                  className="btn btn-primary btn-sm" style={{ width: '100%' }}>
            {t('Бесплатная консультация', 'Free consultation')}
          </button>
          {!user ? (
            <button onClick={() => { setMobileOpen(false); setRoute({ name: 'auth' }); }}
                    className="btn btn-line btn-sm" style={{ width: '100%', color: '#FFFFFF', borderColor: 'rgba(255,255,255,0.3)' }}>
              {t('Войти в личный кабинет', 'Sign in')}
            </button>
          ) : (
            <>
              <button onClick={() => { setMobileOpen(false); setRoute({ name: 'dashboard' }); }}
                      className="btn btn-line btn-sm" style={{ width: '100%', color: '#FFFFFF', borderColor: 'rgba(255,255,255,0.3)' }}>
                {t(`Личный кабинет · ${user.name}`, `Dashboard · ${user.name}`)}
              </button>
              <button onClick={() => { setMobileOpen(false); onLogout(); }}
                      style={{ height: 36, background: 'transparent', color: 'rgba(255,255,255,0.6)', border: 0, fontSize: 12, cursor: 'pointer' }}>
                {t('Выйти', 'Sign out')}
              </button>
            </>
          )}
        </div>
      )}

      {/* Header responsive CSS */}
      <style dangerouslySetInnerHTML={{ __html: `
        @media (max-width: 980px) {
          .header-nav-desktop { display: none !important; }
          .header-only-desktop { display: none !important; }
          .header-burger { display: grid !important; }
        }
        @media (min-width: 981px) {
          .header-mobile-drawer { display: none !important; }
        }
      `}} />
    </header>
  );
}

window.Header = Header;
