// ════════════════════════════════════════════════════════════════
// Header — sticky шапка с wordmark + live pill + 4 stats со sparklines
// ════════════════════════════════════════════════════════════════
const { useState: useStateHeader, useEffect: useEffectHeader } = React;

function useWindowWidth() {
  const [w, setW] = useStateHeader(typeof window !== 'undefined' ? window.innerWidth : 1280);
  useEffectHeader(() => {
    function onR() { setW(window.innerWidth); }
    window.addEventListener('resize', onR);
    return () => window.removeEventListener('resize', onR);
  }, []);
  return w;
}

function Header({ route, onRoute, onToggleTheme, theme, megaOpen, onToggleMega, currentUser, onLogout }) {
  const D = window.SDH_DATA;
  const W = useWindowWidth();
  const isAdmin = currentUser && (currentUser.role === 'super_admin' || currentUser.role === 'admin');

  // Progressive collapse logic (different budget when admin chrome is present)
  // Header container is now max-1760px so we have more room than before
  const showLabels      = W >= (isAdmin ? 1780 : 1280);
  const showSparks      = W >= (isAdmin ? 1480 : 980);
  const visibleStatsCount = isAdmin
    ? (W >= 1780 ? 4 : W >= 1560 ? 2 : W >= 1300 ? 1 : 0)
    : (W >= 1280 ? 4 : W >= 1180 ? 4 : W >= 1020 ? 2 : W >= 880 ? 1 : 0);
  const showLivePillDate = W >= (isAdmin ? 1480 : 1100);
  const showUserName     = W >= (isAdmin ? 1700 : 1180);
  const adminBarLevel    = W >= 1700 ? 'full' : W >= 1080 ? 'compact' : 'icon';
  const showThemeToggle  = W >= 760;

  const allStats = [
    { key: 'startups',   label: 'стартапов',     value: D.series.startups[D.series.startups.length - 1].value,     series: D.series.startups },
    { key: 'classified', label: 'классифицировано', value: D.series.classified[D.series.classified.length - 1].value, series: D.series.classified },
    { key: 'sources',    label: 'источников',    value: D.series.sources[D.series.sources.length - 1].value,       series: D.series.sources },
    { key: 'ideas',      label: 'идей',          value: D.series.ideas[D.series.ideas.length - 1].value,           series: D.series.ideas },
  ];
  // Priority order for narrow widths: startups + ideas first
  const priorityOrder = ['startups', 'ideas', 'classified', 'sources'];
  const stats = priorityOrder.slice(0, visibleStatsCount)
    .map(k => allStats.find(s => s.key === k))
    .filter(Boolean);

  // Primary nav: 3 ежедневных маршрута. Остальное — в мега-меню "Инструменты".
  const primary = [
    { id: 'corpus', label: 'Реестр' },
    { id: 'ideas',  label: 'Идеи' },
    { id: 'trends', label: 'Тренды' },
  ];
  const toolRoutes = ['markets', 'methods', 'costs', 'pricing'];
  const inTools = toolRoutes.includes(route);

  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 50,
      height: 'var(--header-h)',
      background: 'var(--surface-elevated)',
      borderBottom: '1px solid var(--border-subtle)',
      backdropFilter: 'saturate(180%) blur(8px)',
    }}>
      <div style={{
        height: '100%',
        maxWidth: 1760,
        margin: '0 auto',
        padding: '0 var(--space-6)',
        display: 'flex', alignItems: 'center', gap: 'var(--space-4)',
      }}>
        {/* wordmark — clickable home link, collapses to just .DataHub on narrow */}
        <button onClick={() => onRoute('corpus')}
          style={{
            display: 'flex', alignItems: 'baseline', gap: 0, flexShrink: 0,
            background: 'transparent', border: 'none', padding: 0,
            cursor: 'pointer', font: 'inherit',
          }}
          title="На главную">
          {W >= 1100 && (
            <span style={{
              fontFamily: 'var(--font-display)',
              fontStyle: 'italic',
              fontSize: 22,
              fontWeight: 600,
              color: 'var(--text-primary)',
              letterSpacing: '-0.01em',
            }}>Symbiosis</span>
          )}
          <span style={{
            fontFamily: 'var(--font-display)',
            fontStyle: 'italic',
            fontSize: 22,
            fontWeight: 600,
            color: 'var(--brand-bronze-deep)',
            letterSpacing: '-0.01em',
          }}>.DataHub</span>
        </button>

        {/* live pill */}
        <span className="sdh-pill" style={{ flexShrink: 0 }}>
          <span style={{
            width: 7, height: 7, borderRadius: '50%', background: 'var(--success)',
            boxShadow: '0 0 0 2px rgba(107, 142, 90, 0.18)',
            animation: 'sdhPulse 1.8s ease-in-out infinite',
          }} />
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.04em' }}>live</span>
          {showLivePillDate && <span style={{ color: 'var(--text-tertiary)', fontSize: 11 }}>23 мая</span>}
        </span>

        {/* nav: shrinkable, overflow clips when too narrow */}
        <nav style={{
          display: 'flex', gap: 2, marginLeft: 'var(--space-3)',
          flex: '1 1 auto', minWidth: 0,
          overflow: 'hidden',
        }}>
          {primary.map(n => (
            <button key={n.id} onClick={() => onRoute(n.id)}
              className="sdh-btn sdh-btn--ghost"
              style={{
                padding: '6px 10px',
                fontSize: 13,
                color: route === n.id ? 'var(--text-primary)' : 'var(--text-secondary)',
                background: route === n.id ? 'var(--surface-sunken)' : 'transparent',
                fontWeight: route === n.id ? 600 : 500,
                border: '1px solid transparent',
                whiteSpace: 'nowrap',
                flexShrink: 0,
              }}>
              {n.label}
            </button>
          ))}
          {/* Tools mega-menu trigger */}
          <button onClick={onToggleMega}
            className="sdh-btn sdh-btn--ghost"
            style={{
              padding: '6px 8px 6px 10px',
              fontSize: 13,
              color: (inTools || megaOpen) ? 'var(--text-primary)' : 'var(--text-secondary)',
              background: (inTools || megaOpen) ? 'var(--surface-sunken)' : 'transparent',
              fontWeight: (inTools || megaOpen) ? 600 : 500,
              border: '1px solid transparent',
              whiteSpace: 'nowrap',
              gap: 4, flexShrink: 0,
            }}
            aria-expanded={megaOpen}
            title="Инструменты">
            {W >= 1000 ? 'Инструменты' : (
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.3">
                <rect x="2" y="2" width="5" height="5" rx="1" />
                <rect x="9" y="2" width="5" height="5" rx="1" />
                <rect x="2" y="9" width="5" height="5" rx="1" />
                <rect x="9" y="9" width="5" height="5" rx="1" />
              </svg>
            )}
            <svg width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="currentColor" strokeWidth="1.5"
              style={{ transform: megaOpen ? 'rotate(180deg)' : 'none', transition: 'transform .2s' }}>
              <path d="M2 4l3 3 3-3" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </button>
        </nav>

        {/* stats with sparklines */}
        {stats.length > 0 && (
          <div style={{
            display: 'flex', alignItems: 'center', gap: 'var(--space-3)',
            paddingLeft: 'var(--space-3)',
            borderLeft: '1px solid var(--border-subtle)',
            flexShrink: 0,
          }}>
            {stats.map((s, i) => {
              const m = window.METRIC_DICT[s.key];
              const labelEl = showLabels ? (
                m ? (
                  <InfoLabel title={m.title} what={m.what} why={m.why}>
                    <span style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>{s.label}</span>
                  </InfoLabel>
                ) : <span style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>{s.label}</span>
              ) : null;
              return (
              <React.Fragment key={s.key}>
                {i > 0 && <span style={{ color: 'var(--text-tertiary)', opacity: 0.5 }}>·</span>}
                <div style={{ display: 'flex', alignItems: 'center', gap: 5 }} title={!showLabels && m ? `${m.title} — ${m.what}` : undefined}>
                  <span className="sdh-num" style={{
                    fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 500, color: 'var(--text-primary)',
                  }}>{s.value.toLocaleString('ru-RU')}</span>
                  {showSparks && <MicroSparkline data={s.series} width={36} height={11} color="var(--brand-bronze)" />}
                  {labelEl}
                </div>
              </React.Fragment>
              );
            })}
          </div>
        )}

        {/* Admin Quick-Bar */}
        {currentUser && <AdminQuickBar role={currentUser.role} route={route} onRoute={onRoute} level={adminBarLevel} />}

        {/* User chip */}
        {currentUser && (
          <button onClick={() => onRoute('account')}
            className="sdh-btn sdh-btn--ghost"
            style={{
              padding: '4px 8px 4px 4px',
              fontSize: 12, gap: 6,
              border: route === 'account' ? '1px solid var(--brand-bronze)' : '1px solid transparent',
              background: route === 'account' ? 'var(--brand-bronze-subtle)' : 'transparent',
              flexShrink: 0,
            }}>
            <UserAvatar name={currentUser.name} role={currentUser.role} size={24} />
            {showUserName && <span style={{ color: 'var(--text-primary)' }}>{currentUser.name.split(' ')[0]}</span>}
          </button>
        )}

        {/* theme toggle */}
        {showThemeToggle && (
          <button className="sdh-btn sdh-btn--ghost" onClick={onToggleTheme}
            title={theme === 'dark' ? 'Светлая тема' : 'Тёмная тема'}
            style={{ padding: 6, marginLeft: 4, flexShrink: 0 }}>
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4">
              {theme === 'dark'
                ? <circle cx="8" cy="8" r="3.5" fill="currentColor" stroke="none" />
                : <path d="M11.5 9.5 A4 4 0 1 1 6.5 4.5 A3.2 3.2 0 0 0 11.5 9.5z" fill="currentColor" stroke="none" />}
            </svg>
          </button>
        )}
      </div>
      <style>{`
        @keyframes sdhPulse { 0%,100%{opacity:1} 50%{opacity:0.4} }
      `}</style>
    </header>
  );
}

window.Header = Header;
