// Top Navbar
const Navbar = ({ active, onNavigate, onLogout, user, isSuperAdmin, captcha, onRefreshCaptcha, refreshing }) => {
  const allItems = [
    { id: 'profiles', icon: 'layout-grid', label: 'Profiles' },
    { id: 'users', icon: 'users', label: 'Users', superadminOnly: true },
    { id: 'settings', icon: 'sliders-horizontal', label: 'Settings', superadminOnly: true },
    { id: 'captcha', icon: 'shield-check', label: 'Captcha', superadminOnly: true },
    { id: 'hosts', icon: 'globe', label: 'Hosts', superadminOnly: true },
    { id: 'proxies', icon: 'shield', label: 'Proxies', superadminOnly: true },
  ];
  const items = allItems.filter(it => isSuperAdmin || !it.superadminOnly);
  const getInitials = (name) => name?.split(' ').map(n => n[0]).join('').toUpperCase() || '?';
  const providerLabel = captcha?.provider === 'capmonster' ? 'CapMonster' : captcha?.provider ? captcha.provider.charAt(0).toUpperCase() + captcha.provider.slice(1) : 'None';

  const [userMenuOpen, setUserMenuOpen] = React.useState(false);
  const userMenuRef = React.useRef(null);
  React.useEffect(() => {
    if (!userMenuOpen) return;
    const h = (e) => { if (userMenuRef.current && !userMenuRef.current.contains(e.target)) setUserMenuOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, [userMenuOpen]);

  return (
    <nav style={{
      position: 'sticky', top: 0, zIndex: 50,
      background: 'rgba(255,255,255,0.92)', backdropFilter: 'blur(12px)', WebkitBackdropFilter: 'blur(12px)',
      borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center',
      padding: '0 20px', height: 52, gap: 0,
    }}>
      {/* Logo */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginRight: 24, flexShrink: 0 }}>
        <div style={{ width: 28, height: 28, borderRadius: 8, background: 'linear-gradient(135deg,#40D0F0,#30D090)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12 l4 4 l10 -10"/></svg>
        </div>
        <div style={{ fontWeight: 800, fontSize: 15, color: 'var(--fg-1)', letterSpacing: '-0.02em' }}>ivac</div>
        <div style={{ fontSize: 10, color: 'var(--fg-4)', fontWeight: 600, marginLeft: -2 }}>v2.1</div>
      </div>

      {/* Primary nav items */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 2, flex: 1 }}>
        {items.map(it => {
          const is = active === it.id;
          return (
            <button key={it.id} onClick={() => onNavigate?.(it.id)} style={{
              display: 'inline-flex', alignItems: 'center', gap: 6, padding: '6px 12px', borderRadius: 8,
              fontSize: 13, fontWeight: is ? 700 : 500,
              color: is ? 'var(--teal-ink)' : 'var(--fg-2)',
              background: is ? 'var(--teal-50)' : 'transparent',
              border: 'none', cursor: 'pointer', transition: 'background 120ms',
            }}
              onMouseEnter={e => { if (!is) e.currentTarget.style.background = 'var(--bg-hover)'; }}
              onMouseLeave={e => { if (!is) e.currentTarget.style.background = 'transparent'; }}
            >
              <Icon name={it.icon} size={14} color={is ? 'var(--teal)' : 'var(--fg-3)'} />
              {it.label}
            </button>
          );
        })}
      </div>

      {/* Right side: captcha badges + user */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
        {isSuperAdmin && (
          <>
            {/* Reserve Pool badge */}
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 10px',
              borderRadius: 20, background: 'var(--green-50)', border: '1px solid var(--green-100)',
              fontSize: 12, fontWeight: 700, color: 'var(--green-deep)',
            }}>
              <Icon name='shield' size={12} color='var(--green-deep)' />
              <span style={{ fontFamily: 'var(--font-mono)' }}>{captcha?.farm?.reservePool ?? '—'}</span>
              <span style={{ fontWeight: 500, color: 'var(--fg-3)', fontSize: 11 }}>tokens</span>
            </div>

            {/* Fallback provider + balance badge */}
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 10px',
              borderRadius: 20, background: 'var(--orange-50,#FFF7ED)', border: '1px solid var(--orange-100,#FED7AA)',
              fontSize: 12, fontWeight: 700, color: 'var(--orange,#F97316)',
            }}>
              <Icon name='cloud' size={12} color='var(--orange,#F97316)' />
              {providerLabel}
              {captcha?.balance != null && (
                <>
                  <span style={{ width: 1, height: 12, background: 'var(--orange-100,#FED7AA)', margin: '0 2px' }} />
                  <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700 }}>${Number(captcha.balance).toFixed(2)}</span>
                </>
              )}
            </div>

            {/* Refresh button */}
            <button onClick={onRefreshCaptcha} disabled={refreshing} title='Refresh captcha status' style={{
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              width: 30, height: 30, borderRadius: 8, border: '1px solid var(--border)',
              background: '#fff', cursor: refreshing ? 'not-allowed' : 'pointer', color: 'var(--fg-2)',
              opacity: refreshing ? 0.5 : 1,
            }}>
              <Icon name='refresh-cw' size={13} color='var(--fg-2)' className={refreshing ? 'icon-rotating' : ''} />
            </button>

            <div style={{ width: 1, height: 20, background: 'var(--border)' }} />
          </>
        )}

        {/* User avatar + menu */}
        {user && (
          <div ref={userMenuRef} style={{ position: 'relative' }}>
            <button onClick={() => setUserMenuOpen(o => !o)} style={{
              display: 'flex', alignItems: 'center', gap: 8, padding: '4px 8px 4px 4px',
              borderRadius: 10, border: '1px solid var(--border)', background: '#fff', cursor: 'pointer',
            }}>
              <div style={{ width: 26, height: 26, borderRadius: 7, background: 'var(--teal-50)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 700, color: 'var(--teal-ink)' }}>
                {getInitials(user.name || user.username)}
              </div>
              <div style={{ textAlign: 'left' }}>
                <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--fg-1)', lineHeight: 1.2 }}>{user.name || user.username}</div>
                <div style={{ fontSize: 10, color: isSuperAdmin ? 'var(--teal-ink)' : 'var(--fg-3)', fontWeight: isSuperAdmin ? 700 : 400, textTransform: 'uppercase', letterSpacing: '0.04em' }}>
                  {isSuperAdmin ? '⭐ Super Admin' : (user.role || 'Operator')}
                </div>
              </div>
              <Icon name='chevron-down' size={12} color='var(--fg-3)' />
            </button>
            {userMenuOpen && (
              <div style={{
                position: 'absolute', top: 'calc(100% + 6px)', right: 0, minWidth: 160,
                background: '#fff', border: '1px solid var(--border)', borderRadius: 10,
                boxShadow: 'var(--shadow-lg)', overflow: 'hidden', zIndex: 200,
              }}>
                <button onClick={() => { setUserMenuOpen(false); onLogout?.(); }} style={{
                  display: 'flex', alignItems: 'center', gap: 8, width: '100%', padding: '10px 14px',
                  border: 'none', background: 'none', cursor: 'pointer', fontSize: 13, color: 'var(--pink)',
                  fontWeight: 600,
                }}
                  onMouseEnter={e => e.currentTarget.style.background = 'var(--pink-50)'}
                  onMouseLeave={e => e.currentTarget.style.background = 'none'}
                >
                  <Icon name='log-out' size={14} color='var(--pink)' /> Logout
                </button>
              </div>
            )}
          </div>
        )}
      </div>
    </nav>
  );
};

const Topbar = ({ title, subtitle, action }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
    <div>
      <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--fg-1)', letterSpacing: '-0.02em', lineHeight: 1.2 }}>{title}</div>
      {subtitle && <div style={{ fontSize: 13, color: 'var(--fg-3)', marginTop: 4 }}>{subtitle}</div>}
    </div>
    {action}
  </div>
);

// Keep Sidebar exported for backwards compat (unused)
const Sidebar = Navbar;

Object.assign(window, { Sidebar, Navbar, Topbar });
