# WhatsApp Client Reference

## Client Initialization

```javascript
import { Client, LocalAuth, MessageMedia } from 'whatsapp-web.js'

const client = new Client({
  authStrategy: new LocalAuth({ dataPath: './.wwebjs_auth' }),
  puppeteer: {
    headless: true,
    args: [
      '--no-sandbox',              // REQUIRED on Linux VPS
      '--disable-setuid-sandbox',  // REQUIRED on Linux VPS
      '--disable-dev-shm-usage',   // Prevents shared memory issues
      '--disable-gpu',             // No GPU on server
      '--disable-extensions'       // Faster startup
    ]
  }
})
```

## Connection States

```
disconnected → qr_pending → authenticated → connected
                    ↑                            ↓
                    └──── disconnected ←─────────┘
```

## Essential Event Handlers

### QR Code (scan needed)
```javascript
client.on('qr', (qr) => {
  io.emit('qr', qr)
  io.emit('status', { status: 'qr_pending' })
})
```

### Ready (connected)
```javascript
client.on('ready', () => {
  const phone = client.info.wid.user
  io.emit('ready', { status: 'connected', phone })
})
```

### Message (incoming)
```javascript
client.on('message', async (message) => {
  const chat = await message.getChat()
  // ALWAYS filter groups and status broadcasts
  if (chat.isGroup || message.from === 'status@broadcast') return
  await handleMessage(message, client)
})
```

### Disconnected
```javascript
client.on('disconnected', (reason) => {
  io.emit('status', { status: 'disconnected' })
  io.emit('disconnected')
})
```

### Auth Failure
```javascript
client.on('auth_failure', () => {
  io.emit('status', { status: 'auth_failure' })
})
```

## Message Types

| `message.type` | Description | Has Media |
|-----------------|-------------|-----------|
| `'chat'` | Text message | No |
| `'image'` | Photo | Yes |
| `'ptt'` | Voice note (push-to-talk) | Yes |
| `'audio'` | Audio file | Yes |
| `'video'` | Video | Yes |
| `'sticker'` | Sticker | Yes |
| `'document'` | File attachment | Yes |
| `'location'` | GPS location | No |
| `'vcard'` | Contact card | No |

## Downloading Media

```javascript
if (message.hasMedia) {
  const media = await message.downloadMedia()
  // media.mimetype → 'image/jpeg', 'audio/ogg; codecs=opus', etc.
  // media.data     → base64 string (NO data URI prefix)
  // media.filename → original filename (may be null)

  // Store as data URI:
  const dataUri = `data:${media.mimetype};base64,${media.data}`
}
```

## Sending Messages

### Text
```javascript
await client.sendMessage(phone, 'Hello!')
```

### Image
```javascript
const media = new MessageMedia('image/png', base64Data, 'photo.png')
await client.sendMessage(phone, media, { caption: 'Here is your photo!' })
```

### Audio (as voice note)
```javascript
const media = new MessageMedia('audio/ogg; codecs=opus', base64Data, 'audio.ogg')
await client.sendMessage(phone, media, { sendAudioAsVoice: true })
```

### Document
```javascript
const media = new MessageMedia('application/pdf', base64Data, 'report.pdf')
await client.sendMessage(phone, media)
```

## Logout (clear session)

```javascript
async function logout() {
  if (client) {
    await client.logout()   // Removes .wwebjs_auth/ data
    connectionStatus = 'disconnected'
  }
}
```

## Phone Number Format

WhatsApp numbers include country code and `@c.us` suffix:
- `5511999999999@c.us` (Brazil: +55 11 99999-9999)
- `message.from` always has this format
- `client.info.wid.user` returns just the number without `@c.us`

## Common Pitfalls

1. **Session crash**: If `.wwebjs_auth/` gets corrupted, delete it and re-scan QR
2. **Puppeteer memory**: whatsapp-web.js uses ~300-500MB RAM (Chromium process)
3. **Message ordering**: Messages arrive async, use session state to track position
4. **Media timeout**: Large files may timeout — add try/catch around `downloadMedia()`
5. **Rate limiting by WhatsApp**: Don't send too many messages too fast (risk of ban)
