# Sync Button - Complete Guide

## 🔄 Overview

The sync button provides **manual synchronization** between local device storage and the server database. It works on both **HTTPS (production)** and **HTTP (local network)** connections across all devices.

---

## ✨ Features

### 1. **Manual Sync Button**

- **Location**: Top navigation bar (desktop) and mobile hamburger menu
- **Function**: Bidirectional sync (push local changes + pull server changes)
- **Use Case**: When internet connection was lost and you need to sync after reconnecting

### 2. **Auto-Sync (Background)**

- **Polling Interval**: Every 5 seconds
- **Function**: Automatically checks for server changes and updates all devices
- **Mode**: Only works in **Online Mode**

---

## 🎯 How It Works

### Manual Sync Process

1. **Press Sync Button** (🔄 icon in navigation)
2. **Upload Phase**: Pushes all local changes to server
   - Songs created/modified
   - Profiles created/modified
   - Worship lists created/modified
   - Profile-song associations
   - Custom song keys per profile
3. **Download Phase**: Pulls all server changes to local device
   - Merges with existing local data
   - Deduplicates by ID
4. **Success Notification**: Shows ✅ confirmation

### Auto-Sync Process (Background)

- Runs automatically every 5 seconds in Online Mode
- Triggers refresh events across all components
- No user action needed
- Keeps all devices synchronized in real-time

---

## 📱 Multi-Device Support

### Supported Configurations

| Device Type | HTTPS (Production) | HTTP (Local) |
|------------|-------------------|--------------|
| Desktop PC | ✅ <https://houseofprayer.ddns.net> | ✅ <http://localhost:5100> |
| Phone | ✅ <https://houseofprayer.ddns.net> | ✅ <http://192.168.10.178:5100> |
| Tablet | ✅ <https://houseofprayer.ddns.net> | ✅ <http://192.168.10.178:5100> |
| Laptop | ✅ <https://houseofprayer.ddns.net> | ✅ <http://192.168.10.178:5100> |

---

## 🔧 Setup Requirements

### For Sync to Work

1. **Online Mode Enabled**
   - Go to **Settings** → **Access Mode**
   - Select **"Online Mode (Multi-Device Sync)"**
   - Click **Save Settings**

2. **Backend Connection**
   - Settings → **Online/DNS Settings**
   - Protocol: `http` or `https`
   - Hostname: `houseofprayer.ddns.net` (production) or local IP
   - Port: `8080` (backend) or `5100` (frontend)

3. **Internet Connection**
   - For HTTPS: Requires internet
   - For HTTP Local: Requires WiFi on same network

---

## 💡 Use Cases

### Scenario 1: Lost WiFi Connection

1. WiFi drops while editing songs
2. Changes saved to local storage automatically
3. WiFi reconnects
4. **Press Sync Button** to upload changes to server
5. ✅ All devices now have your changes

### Scenario 2: Working Offline

1. Switch to **Local Mode** in Settings
2. Create/edit songs, worship lists, profiles
3. Later, switch back to **Online Mode**
4. **Press Sync Button** to upload everything
5. ✅ Data now synced across all devices

### Scenario 3: Multiple People Editing

- **Person A** adds songs on desktop
- **Person B** creates worship list on phone
- Auto-sync updates both devices every 5 seconds
- No manual sync needed (happens automatically)
- **Use Sync Button** if connection was unstable

---

## 🚨 Troubleshooting

### Sync Button Says "Only Available in Online Mode"

**Problem**: App is in Local Mode  
**Solution**:

1. Go to **Settings**
2. Select **"Online Mode (Multi-Device Sync)"**
3. Click **Save Settings**
4. Try sync button again

### Sync Fails with Error

**Problem**: Cannot reach backend server  
**Solution**:

1. Check internet/WiFi connection
2. Verify Settings → Online/DNS Settings are correct
3. Check backend is running: `sudo systemctl status church-music-backend`
4. Test API directly:
   - Production: <https://houseofprayer.ddns.net/api/health>
   - Local: <http://localhost:8080/api/health>

### Auto-Sync Not Working

**Problem**: Changes from other devices not appearing  
**Solution**:

1. Verify **Online Mode** is enabled in Settings
2. Check connection status (green dot vs red dot in top navigation)
3. Try manual sync button to force refresh
4. Check browser console (F12) for errors

### Data Conflicts

**Problem**: Same data edited on two devices simultaneously  
**Solution**:

- Backend is source of truth
- Local changes merge with backend on sync
- Deduplication by ID prevents duplicates
- Later edits overwrite earlier ones
- No data is lost (both versions attempted)

---

## 🎨 Visual Indicators

### Connection Status (Top Navigation)

| Indicator | Meaning |
|-----------|---------|
| 🟢 Online | Connected to backend server |
| 🔴 Offline | No backend connection |

### Sync Feedback

| Message | Meaning |
|---------|---------|
| ✅ Sync complete! | Successful sync (desktop) |
| ✅ Sync complete! Your changes are now on the server. | Successful sync (mobile) |
| ❌ Sync failed: [error] | Connection or server error |
| ⚠️ Sync is only available in Online Mode | Need to enable Online Mode |

---

## 📊 What Gets Synced

### Data Types

- ✅ **Songs**: Title, lyrics, chords, key, tempo, time signature
- ✅ **Profiles**: Name, description, settings
- ✅ **Worship Lists**: Date, notes, profile association
- ✅ **Song Assignments**: Which songs in which worship lists
- ✅ **Profile Songs**: Favorite songs per profile
- ✅ **Custom Keys**: Transposed keys per profile-song combination

### Sync Operations

| Operation | Upload (Local → Server) | Download (Server → Local) |
|-----------|-------------------------|---------------------------|
| **New Items** | Creates on server | Creates locally |
| **Modified Items** | Updates server | Updates local |
| **Deleted Items** | Not synced (manual delete only) | Not synced |
| **Conflicts** | Latest timestamp wins | Backend is source of truth |

---

## ⚡ Performance

### Sync Speed

- **Small datasets** (< 100 songs): < 2 seconds
- **Medium datasets** (100-500 songs): 2-5 seconds
- **Large datasets** (> 500 songs): 5-10 seconds

### Network Requirements

- **Minimum**: 1 Mbps upload/download
- **Recommended**: 5+ Mbps for smooth operation
- **Latency**: < 500ms for responsive sync

---

## 🔐 Security

### Data Protection

- HTTPS encryption in production
- JWT authentication tokens
- Profile-based access control
- No sensitive data in localStorage
- Passwords hashed (never synced)

### Privacy

- Sync only when authenticated
- Data isolated per user account
- No cross-user data leakage
- Local fallback if server unreachable

---

## 📝 Code Reference

### Sync Functions

**Location**: `frontend/src/migration.js`

```javascript
// Full bidirectional sync
fullSync(customBase)
  - migrateLocalStorageToBackend() // Upload
  - syncFromBackendToLocalStorage() // Download

// Manual upload only
migrateLocalStorageToBackend(customBase)

// Manual download only
syncFromBackendToLocalStorage(customBase)
```

### Sync Button Implementation

**Location**: `frontend/src/App.js`

- **Desktop**: Line ~7538 (top navigation)
- **Mobile**: Line ~7831 (hamburger menu)

Both buttons call `fullSync()` from migration.js

### Auto-Sync Polling

**Location**: `frontend/src/App.js` line ~7178

```javascript
// Polls every 5 seconds in Online Mode
useEffect(() => {
  if (!isAuthenticated) return;
  let syncTimer;
  async function pollForChanges() {
    // Dispatch refresh events
    window.dispatchEvent(new Event("songsChanged"));
    window.dispatchEvent(new Event("plansChanged"));
    window.dispatchEvent(new Event("profileChanged"));
  }
  syncTimer = setInterval(pollForChanges, 5000);
  return () => clearInterval(syncTimer);
}, [isAuthenticated]);
```

---

## 🎯 Best Practices

### For Reliable Sync

1. **Enable Online Mode** when connected to internet/WiFi
2. **Use Local Mode** only when working completely offline
3. **Press Sync Button** after switching from Local to Online Mode
4. **Wait for confirmation** (✅ message) before closing app
5. **Check connection indicator** (green dot) before creating important data

### For Multi-Device Teams

1. **One person per task** - avoid simultaneous edits
2. **Refresh before editing** - ensure you have latest data
3. **Save frequently** - changes auto-sync every 5 seconds
4. **Use Sync Button** if connection was unstable
5. **Coordinate worship list creation** - avoid duplicate lists

---

## 🚀 Deployment

Deployed: December 17, 2025 23:18 CST  
Version: v=2380  
Bundle: main.bf5e2e29.js (114.15 kB gzipped)

### Access URLs

- **Production (HTTPS)**: <https://houseofprayer.ddns.net>
- **Local Network (HTTP)**: <http://192.168.10.178:5100>
- **Localhost**: <http://localhost:5100>

---

## 📞 Support

If sync issues persist:

1. Check [TROUBLESHOOTING.md](TROUBLESHOOTING.md)
2. Review browser console logs (F12 → Console)
3. Test backend health: `/api/health` endpoint
4. Verify systemd services running:

   ```bash
   sudo systemctl status church-music-backend
   sudo systemctl status church-music-frontend
   ```
