# Offline Form Submission Troubleshooting Guide

**Last Updated:** 2026-01-12

## Common Issues and Solutions

### Submissions Not Syncing

**Symptoms:**

- Submissions queued but not syncing when back online
- Offline indicator shows pending submissions but they don't sync

**Solutions:**

1. **Check Network Status:**

   - Open browser console (F12)
   - Check if health check endpoint is accessible: `fetch('/v2/api/health-check.php')`
   - Verify network status cache is not stale

2. **Verify Background Sync:**

   - Check if Background Sync API is supported: `'sync' in ServiceWorkerRegistration.prototype`
   - If not supported, fallback to polling (every 30 seconds)
   - Wait up to 30 seconds for polling to trigger

3. **Check Browser Console:**

   - Look for JavaScript errors
   - Check for storage errors (IndexedDB/localStorage)
   - Verify StorageManager initialized correctly

4. **Manual Retry:**

   - Click "Erneut versuchen" button in offline indicator
   - This resets failed submissions to pending status

5. **Clear Storage and Retry:**
   - Open browser DevTools → Application → IndexedDB
   - Delete `EventLeadCaptureDB` database
   - Refresh page (will recreate database)
   - Re-submit form

### Storage Quota Exceeded

**Symptoms:**

- Error: "Storage quota exceeded"
- Submissions not being saved

**Solutions:**

1. **Automatic Cleanup:**

   - System automatically removes synced submissions older than 7 days
   - System enforces max 100 submissions limit
   - Oldest submissions deleted first

2. **Manual Cleanup:**

   - Open browser DevTools → Application → IndexedDB
   - Open `EventLeadCaptureDB` → `event_submissions`
   - Delete old synced submissions manually
   - Or delete entire database and refresh

3. **Check Storage Usage:**
   - Use `storageManager.getStorageInfo()` in console
   - Check total count and status breakdown
   - Identify which submissions can be safely removed

### Duplicate Submissions

**Symptoms:**

- Same submission appears multiple times in queue
- Duplicate submissions synced to HubSpot

**Solutions:**

1. **Check Hash Generation:**

   - Hash based on: `email + event_id + 5-minute time window`
   - Submissions within 5 minutes with same email/event are considered duplicates
   - Verify hash calculation is working correctly

2. **Verify Merge Logic:**

   - Duplicates should be merged (not queued separately)
   - Most complete data kept from both submissions
   - Check console logs for merge operations

3. **Manual Deduplication:**
   - Open IndexedDB and check for duplicate hashes
   - Manually delete duplicates if needed

### Network Detection Not Working

**Symptoms:**

- Form thinks it's offline when actually online
- Form thinks it's online when actually offline

**Solutions:**

1. **Check Health Check Endpoint:**

   - Verify `/v2/api/health-check.php` is accessible
   - Should return: `{"status":"ok","timestamp":...}`
   - Check server logs for errors

2. **Clear Network Cache:**

   - Network status cached for 10 seconds
   - Wait 10 seconds or refresh page to clear cache
   - Or manually clear: `offlineSync.networkStatusCache = null`

3. **Verify Navigator.onLine:**
   - Check `navigator.onLine` value in console
   - Note: This is unreliable, actual fetch test is more accurate

### Background Sync Not Working

**Symptoms:**

- Submissions not syncing when tab is closed
- Background Sync API not triggering

**Solutions:**

1. **Check Browser Support:**

   - Background Sync requires HTTPS (or localhost)
   - Not supported in all browsers
   - Falls back to polling if unavailable

2. **Verify Service Worker:**

   - Check if service worker is registered
   - Verify sync event listener is registered
   - Check service worker logs

3. **Manual Sync:**
   - Use polling fallback (every 30 seconds)
   - Or manually trigger: `offlineSync.syncQueue()`

### Failed Submissions After Max Retries

**Symptoms:**

- Submissions marked as "needs attention" after 10 retry attempts
- Not syncing automatically

**Solutions:**

1. **Check Error Type:**

   - Non-retryable errors (4xx) marked as failed immediately
   - Retryable errors retried up to 10 times
   - After 10 attempts, marked as "needs attention"

2. **Manual Retry:**

   - Click "Erneut versuchen" button
   - Resets attempts to 0 and status to pending
   - Will retry on next sync cycle

3. **Check Error Details:**
   - Open IndexedDB → `event_submissions`
   - Check `lastError` and `lastErrorType` fields
   - Identify root cause of failures

## Manual Operations

### Clear Offline Queue

**Method 1: Via Browser DevTools**

1. Open DevTools (F12)
2. Go to Application → IndexedDB
3. Delete `EventLeadCaptureDB` database
4. Refresh page

**Method 2: Via Console**

```javascript
// Get storage manager instance
const storageManager = window.eventForm.offlineSync.storageManager;

// Get all submissions
const all = await storageManager.getAll();

// Delete all
for (const submission of all) {
  await storageManager.delete(submission.id);
}
```

### Manually Trigger Sync

**Via Console:**

```javascript
// Get offline sync instance
const offlineSync = window.eventForm.offlineSync;

// Trigger sync
await offlineSync.syncQueue();
```

**Via UI:**

- Click "Erneut versuchen" button in offline indicator

### Check Storage Status

**Via Console:**

```javascript
// Get storage manager instance
const storageManager = window.eventForm.offlineSync.storageManager;

// Get storage info
const info = await storageManager.getStorageInfo();
console.log(info);
// Returns: { total, pending, failed, synced, needsAttention, storageType }
```

**Via Browser DevTools:**

1. Open DevTools → Application → IndexedDB
2. Open `EventLeadCaptureDB` → `event_submissions`
3. View all submissions and their status

### Export Queued Submissions

**Via Console:**

```javascript
// Get all submissions
const storageManager = window.eventForm.offlineSync.storageManager;
const all = await storageManager.getAll();

// Export as JSON
const json = JSON.stringify(all, null, 2);
console.log(json);

// Or download as file
const blob = new Blob([json], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "offline-submissions.json";
a.click();
```

## Debug Mode

**Enable Debug Mode:**

- Add `?debug=1` to URL
- Enables detailed console logging
- Logs all offline operations, sync attempts, errors

**Debug Information:**

- Submission queued/synced events
- Network status checks
- Storage operations
- Error details with stack traces
- Retry attempts and delays

## Browser-Specific Issues

### iPad Safari

**Known Issues:**

- IndexedDB may have stricter quota limits
- Background Sync may not work in all iOS versions
- Service Worker support varies by iOS version

**Workarounds:**

- Falls back to localStorage if IndexedDB fails
- Falls back to polling if Background Sync unavailable
- Test on actual device (not simulator)

### Android Chrome

**Known Issues:**

- Background Sync requires user interaction
- May not sync if browser is force-closed
- Storage quota varies by device

**Workarounds:**

- Ensure user interaction before queuing submission
- Don't force-close browser during sync
- Monitor storage usage

## Getting Help

If issues persist:

1. **Collect Debug Information:**

   - Enable debug mode (`?debug=1`)
   - Copy console logs
   - Check IndexedDB contents
   - Note browser/device information

2. **Check Server Logs:**

   - Review `/v2/logs/event-lead-capture-*.log`
   - Check for API errors
   - Verify HubSpot API connectivity

3. **Contact Support:**
   - Provide debug logs
   - Include browser/device details
   - Describe exact steps to reproduce
