File size: 1,855 Bytes
a281968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Phase 6.3 — Settings Sync
// Loads cloud settings on login and pushes changes with debounce.
// localStorage is always applied first; cloud overrides only when authenticated.

const SETTINGS_PUSH_DEBOUNCE_MS = 1500;
let _settingsPushTimer = null;

/**
 * Load settings from cloud and apply them locally.
 * Called once after auth is initialized.
 */
async function syncSettings() {
  const isAuthenticated = window.__bayanAuth &&
    window.__bayanAuth.userId &&
    !window.__bayanAuth.isOfflineMode;

  if (!isAuthenticated) return;

  const settings = await loadSettings();
  if (!settings) return;

  // Apply theme from cloud (overrides localStorage when authenticated)
  if (settings.theme && typeof setTheme === 'function') {
    setTheme(settings.theme);
  }
}

/**
 * Push a settings change to cloud after a debounce delay.
 * @param {string} key - e.g. 'theme'
 * @param {string|object} value
 */
function onSettingsChanged(key, value) {
  if (_settingsPushTimer) clearTimeout(_settingsPushTimer);
  _settingsPushTimer = setTimeout(async () => {
    const isAuthenticated = window.__bayanAuth &&
      window.__bayanAuth.userId &&
      !window.__bayanAuth.isOfflineMode;
    if (!isAuthenticated) return;
    await saveSettings({ [key]: value });
  }, SETTINGS_PUSH_DEBOUNCE_MS);
}

/**
 * Listen to theme changes from theme.js and push to cloud.
 */
function _bindSettingsListeners() {
  window.addEventListener('bayan:themechange', (e) => {
    if (e.detail && e.detail.theme) {
      onSettingsChanged('theme', e.detail.theme);
    }
  });

  // Re-sync when user signs in (auth state change)
  window.addEventListener('bayan:authchange', () => {
    syncSettings();
  });
}

/**
 * Initialize settings sync. Called once in DOMContentLoaded.
 */
async function initSettingsSync() {
  _bindSettingsListeners();
  await syncSettings();
}