File size: 5,547 Bytes
41e1749
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a281968
41e1749
 
 
 
a281968
 
41e1749
 
 
 
a281968
 
 
 
 
 
 
 
 
41e1749
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9bc964f
 
 
 
41e1749
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a281968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41e1749
 
 
 
 
 
 
 
 
 
a281968
 
 
41e1749
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
// Authentication actions — guest, Google, link, logout

/**
 * Promise with timeout
 * @param {Promise} promise
 * @param {number} ms
 * @param {string} message
 */
function withTimeout(promise, ms, message) {
  return Promise.race([
    promise,
    new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms))
  ]);
}

/**
 * Sign in as anonymous guest
 * @returns {Promise<{ success: boolean, offline?: boolean, error?: string }>}
 */
async function signInAsGuest() {
  const client = getSupabaseClient();
  if (!client) {
    enableOfflineAuthMode();
    return { success: false, offline: true, error: 'not_configured' };
  }

  try {
    const response = await withTimeout(
      client.auth.signInAnonymously(),
      AUTH_SIGN_IN_TIMEOUT_MS,
      'timeout'
    );
    
    const { data, error } = response;
    if (error) throw error;

    setCurrentSession(data.session);
    clearOfflineAuthMode();
    
    // Manually update UI and dispatch event since onAuthStateChange might not fire reliably
    if (typeof updateAuthUI === 'function') {
      updateAuthUI(data.user);
    }
    window.dispatchEvent(new CustomEvent('bayan:authchange', { 
      detail: { event: 'SIGNED_IN', session: data.session } 
    }));

    return { success: true };
  } catch (err) {
    console.warn('Guest sign-in failed:', err);
    enableOfflineAuthMode();
    return { success: false, offline: true, error: err.message || 'failed' };
  }
}

/**
 * Sign in with Google OAuth
 * @returns {Promise<{ success: boolean, error?: string }>}
 */
async function signInWithGoogle() {
  const client = getSupabaseClient();
  if (!client) {
    if (typeof showDocToast === 'function') {
      showDocToast('خدمة المصادقة غير مهيأة. راجع إعدادات Supabase.', 'error');
    }
    return { success: false, error: 'not_configured' };
  }

  const redirectTo = window.location.origin + window.location.pathname;

  try {
    const { error } = await client.auth.signInWithOAuth({
      provider: 'google',
      options: {
        redirectTo,
        queryParams: { prompt: 'select_account' }
      }
    });

    if (error) throw error;
    return { success: true };
  } catch (err) {
    console.error('Google sign-in failed:', err);
    if (typeof showDocToast === 'function') {
      showDocToast('تعذر بدء تسجيل الدخول عبر Google', 'error');
    }
    return { success: false, error: err.message };
  }
}

/**
 * Link Google identity to current anonymous user
 * @returns {Promise<{ success: boolean, error?: string }>}
 */
async function linkGoogle() {
  const client = getSupabaseClient();
  const session = getCurrentSession();

  if (!client || !session) {
    return signInWithGoogle();
  }

  const redirectTo = window.location.origin + window.location.pathname;

  try {
    if (typeof client.auth.linkIdentity === 'function') {
      const { error } = await client.auth.linkIdentity({
        provider: 'google',
        options: { redirectTo }
      });
      if (error) throw error;
      return { success: true };
    }

    return signInWithGoogle();
  } catch (err) {
    console.warn('linkIdentity failed, falling back to signInWithGoogle:', err.message);
    // linkIdentity often fails when manual linking is disabled in Supabase.
    // Fall back to a full Google sign-in instead of showing an error.
    return signInWithGoogle();
  }
}

/**
 * Sign out current user
 * @returns {Promise<void>}
 */
async function signOut() {
  const client = getSupabaseClient();
  if (client) {
    try {
      await client.auth.signOut();
    } catch (err) {
      console.warn('signOut error:', err);
    }
  }

  setCurrentSession(null);
  clearOfflineAuthMode();

  if (typeof updateAuthUI === 'function') {
    updateAuthUI(null);
  }

  // Redirect to main page on logout
  if (typeof showPage === 'function') {
    showPage('home');
  } else if (window.showPage) {
    window.showPage('home');
  }

  window.dispatchEvent(new CustomEvent('bayan:authchange', {
    detail: { event: 'SIGNED_OUT', session: null }
  }));
  showAuthGate();
}

/**
 * Enable offline / degraded auth mode — editor still usable
 */
function enableOfflineAuthMode() {
  window.__bayanAuth = window.__bayanAuth || {};
  window.__bayanAuth.isOfflineMode = true;
  window.__bayanAuth.userId = null;
  // Update nav to show guest menu with Google sign-in option
  if (typeof updateAuthUI === 'function') updateAuthUI(null);
  // showAuthOfflineBanner(true) intentionally omitted — button handler manages UX
}

function clearOfflineAuthMode() {
  if (window.__bayanAuth) {
    window.__bayanAuth.isOfflineMode = false;
  }
  showAuthOfflineBanner(false);
}

/**
 * Initialize authentication — non-blocking for editor
 * @returns {Promise<void>}
 */
async function initAuth() {
  window.__bayanAuth = {
    userId: null,
    isGuest: false,
    isGoogleUser: false,
    isOfflineMode: false,
    getAccessToken: () => null
  };

  bindAuthUIEvents();

  const config = getSupabaseConfig();
  if (!config.isConfigured) {
    enableOfflineAuthMode();
    return;
  }

  onAuthStateChange((event, session) => {
    updateAuthUI(session && session.user ? session.user : null);

    if (event === 'SIGNED_IN' && session) {
      hideAuthGate();
      clearOfflineAuthMode();
    }

    if (event === 'SIGNED_OUT') {
      showAuthGate();
    }
  });

  const session = await restoreSession();

  if (session && session.user) {
    hideAuthGate();
    updateAuthUI(session.user);
    return;
  }

  showAuthGate();
}