# Background Notifications & Real-Time Sound - Testing Guide

## What Was Fixed

### 1. **Service Worker Registration**
- ✅ Added automatic service worker registration in `app.blade.php`
- ✅ Created `sw-register.js` for proper service worker initialization
- ✅ Service worker now registers on page load

### 2. **Background Notifications**
- ✅ Service worker properly handles background messages
- ✅ Notifications show even when browser tab is closed/minimized
- ✅ Click handling works correctly (opens/focuses app)

### 3. **Real-Time Sound**
- ✅ **Foreground**: Sound plays immediately when notification received
- ✅ **Background**: Browser plays system notification sound automatically
- ✅ Sound configured with `silent: false` in both foreground and service worker

## How It Works

### Foreground (App Open)
1. Message received via `onMessage` listener
2. **Sound plays immediately** via `playNotificationSound()`
3. Browser notification shown with `silent: false`
4. Notification data reloaded in UI

### Background (App Closed/Minimized)
1. Service worker receives message via `onBackgroundMessage`
2. Service worker shows notification with `silent: false`
3. **Browser plays system notification sound automatically**
4. Click opens/focuses the app

## Testing Steps

### Step 1: Clear Browser Cache
```
1. Open DevTools (F12)
2. Go to Application tab
3. Click "Clear storage"
4. Check all boxes
5. Click "Clear site data"
6. Refresh page (Ctrl+F5)
```

### Step 2: Check Service Worker Registration
```
1. Open DevTools (F12)
2. Go to Application > Service Workers
3. You should see: firebase-messaging-sw.js (activated and running)
4. Check Console for: "Service Worker registered successfully"
```

### Step 3: Grant Notification Permission
```
1. Login to the app
2. Click "Allow" when prompted for notifications
3. Check Console for: "Notification permission granted"
4. Check Console for: "FCM token stored successfully"
```

### Step 4: Test Foreground Notifications
```
1. Keep browser tab OPEN and FOCUSED
2. Trigger a notification (e.g., assign yourself a task)
3. Expected:
   ✅ Hear notification sound immediately
   ✅ See browser notification popup
   ✅ See notification in topbar dropdown
```

### Step 5: Test Background Notifications
```
1. Keep browser tab OPEN but switch to another tab
2. Trigger a notification
3. Expected:
   ✅ Hear system notification sound
   ✅ See system notification (Windows/Mac notification center)
   ✅ Click notification opens the app

OR

1. Minimize the browser completely
2. Trigger a notification
3. Expected:
   ✅ Hear system notification sound
   ✅ See system notification
   ✅ Click notification opens browser and focuses app
```

### Step 6: Test Sound Volume
```
1. Check system volume is not muted
2. Check browser notification settings allow sound
3. Test notification - should hear sound clearly
```

## Troubleshooting

### No Sound in Foreground
**Problem**: Notification shows but no sound plays

**Solutions**:
1. Check browser console for audio errors
2. Ensure `/sounds/notification.wav` exists
3. Try clicking anywhere on page first (browser autoplay policy)
4. Check browser volume/mute settings

### No Sound in Background
**Problem**: Background notification shows but silent

**Solutions**:
1. **Windows**: 
   - Settings > System > Notifications
   - Ensure notifications are enabled for your browser
   - Ensure "Play a sound" is checked
   
2. **Mac**:
   - System Preferences > Notifications
   - Find your browser
   - Ensure "Play sound for notifications" is checked

3. **Browser Settings**:
   - Chrome: Settings > Privacy > Site Settings > Notifications
   - Ensure sound is enabled for notifications

### Service Worker Not Registering
**Problem**: Console shows service worker errors

**Solutions**:
1. Ensure you're on HTTPS or localhost
2. Clear browser cache completely
3. Check `/firebase-messaging-sw.js` is accessible
4. Unregister old service workers:
   ```javascript
   navigator.serviceWorker.getRegistrations().then(registrations => {
       registrations.forEach(r => r.unregister())
   })
   ```
5. Refresh page

### Background Notifications Not Showing
**Problem**: No notifications when app is in background

**Solutions**:
1. Verify service worker is active (DevTools > Application > Service Workers)
2. Check browser notification permission is granted
3. Ensure FCM token is stored in database
4. Check service worker console for errors
5. Test with simple notification first

### Token Not Stored
**Problem**: Console shows "No FCM tokens found for user"

**Solutions**:
1. Check `/api/fcm/subscribe` endpoint is working
2. Verify user is authenticated
3. Check database `user_fcm_tokens` table
4. Re-grant notification permission

## Browser Console Commands

### Check Service Worker Status
```javascript
navigator.serviceWorker.getRegistrations().then(registrations => {
    console.log('Registered service workers:', registrations)
})
```

### Check Notification Permission
```javascript
console.log('Notification permission:', Notification.permission)
```

### Manually Request Permission
```javascript
Notification.requestPermission().then(permission => {
    console.log('Permission:', permission)
})
```

### Test Notification Sound
```javascript
const audio = new Audio('/sounds/notification.wav')
audio.play()
```

### Check FCM Token
```javascript
// In browser console after login
// Token should be logged when you grant permission
```

## Database Verification

### Check Stored Tokens
```sql
-- View all tokens
SELECT * FROM user_fcm_tokens;

-- View tokens for specific user
SELECT * FROM user_fcm_tokens WHERE user_id = 1;

-- Check token details
SELECT 
    u.name,
    u.email,
    f.device_type,
    f.browser,
    f.platform,
    f.created_at,
    f.last_used_at
FROM user_fcm_tokens f
JOIN users u ON f.user_id = u.id;
```

## Expected Console Logs

### On Page Load
```
Service Worker registered successfully: ServiceWorkerRegistration {...}
Service Worker is ready
```

### On Permission Grant
```
Notification permission granted
Firebase token: [long token string]
FCM token stored successfully
```

### On Foreground Notification
```
Message received in foreground: {notification: {...}, data: {...}}
[Audio plays]
```

### On Background Notification
```
[In Service Worker Console]
[firebase-messaging-sw.js] Received background message: {...}
[System notification sound plays]
```

## Sound Configuration

### Foreground Sound
- File: `/sounds/notification.wav`
- Played by: JavaScript `Audio` API
- Volume: 0.5 (50%)
- Trigger: Immediate on message receive

### Background Sound
- Played by: Browser/OS notification system
- Configured: `silent: false` in service worker
- Volume: System notification volume
- Trigger: Automatic when notification shown

## Important Notes

1. **HTTPS Required**: Service workers only work on HTTPS or localhost
2. **Permission Required**: User must grant notification permission
3. **Browser Differences**: Sound behavior varies by browser/OS
4. **Autoplay Policy**: First sound may require user interaction
5. **System Settings**: OS notification settings affect background sound

## Success Criteria

✅ Service worker registered and active
✅ FCM token stored in database
✅ Foreground notifications play sound immediately
✅ Background notifications show with system sound
✅ Notifications clickable and navigate correctly
✅ Multiple devices receive notifications
✅ Tokens cleaned up on logout

## Next Steps

1. Clear browser cache
2. Refresh the page
3. Grant notification permission
4. Test foreground notification
5. Test background notification
6. Verify sound plays in both cases
