File size: 13,636 Bytes
a281968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed2cae2
a281968
 
ed2cae2
a281968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a06042
 
 
 
 
 
 
 
a281968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
780b95e
 
 
db7f13a
a281968
 
 
 
 
db7f13a
 
a281968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a06042
 
 
 
 
 
 
 
 
 
 
a281968
6a06042
a281968
 
6a06042
a281968
 
 
 
 
6a06042
a281968
 
 
6a06042
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
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
// Phase 6.1 — Documents UI
// All DOM interaction for the docs sidebar.
// Uses only: getEditorText(), loadDocumentText(), documents-api, documents-state.

let _renameDocId = null;

/* ── Initialization ── */

function initDocumentsCloud() {
  _renderSidebar();
  _bindSidebarToggle();
  _bindEditorDirty();
  _loadAndRenderList();

  // Listen to auth changes — reload list when user signs in
  window.addEventListener('bayan:docstate', () => _updateTitleBar());
  window.addEventListener('bayan:authchange', () => {
    _loadAndRenderList();
  });

  // Warn user if they try to refresh with unsaved changes
  window.addEventListener('beforeunload', (e) => {
    const state = getDocState();
    if (state.hasUnsavedChanges) {
      e.preventDefault();
      e.returnValue = '';
    }
  });

  // Sync Manager UI Updates
  window.addEventListener('bayan:syncstate', (e) => {
    const { state } = e.detail;
    const saveBtn = document.getElementById('doc-save-btn');
    if (!saveBtn) return;
    
    if (state === 'saving') {
      saveBtn.title = 'جاري الحفظ...';
      saveBtn.classList.add('is-saving');
      if (typeof showAutoSaveStatus === 'function') showAutoSaveStatus('جاري الحفظ...');
    } else if (state === 'saved') {
      saveBtn.title = 'تم الحفظ';
      if (typeof showAutoSaveStatus === 'function') showAutoSaveStatus('✓ تم الحفظ');
      saveBtn.classList.remove('is-saving', 'doc-save-btn--dirty');
      saveBtn.classList.add('is-saved');
      setTimeout(() => {
        saveBtn.classList.remove('is-saved');
        const currentState = getDocState();
        saveBtn.title = currentState.hasUnsavedChanges ? 'حفظ (يوجد تغييرات غير محفوظة)' : 'حفظ';
      }, 2000);
    } else if (state === 'saved_locally') {
      saveBtn.title = 'محفوظ محلياً (أنت غير متصل)';
      saveBtn.classList.add('doc-save-btn--dirty');
    } else if (state === 'error') {
      saveBtn.title = 'خطأ في الحفظ';
      saveBtn.classList.add('doc-save-btn--dirty');
    }
  });
}

/* ── Sidebar toggle ── */

function _bindSidebarToggle() {
  const toggleBtn = document.getElementById('docs-sidebar-toggle');
  const sidebar = document.getElementById('docs-sidebar');
  if (!toggleBtn || !sidebar) return;

  toggleBtn.addEventListener('click', () => {
    const isOpen = sidebar.classList.toggle('is-open');
    toggleBtn.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
  });

  // Close when clicking outside
  document.addEventListener('click', (e) => {
    if (sidebar && sidebar.classList.contains('is-open') &&
        !sidebar.contains(e.target) &&
        !toggleBtn.contains(e.target)) {
      sidebar.classList.remove('is-open');
      toggleBtn.setAttribute('aria-expanded', 'false');
    }
  });
}

/* ── Mark dirty on editor input ── */

function _bindEditorDirty() {
  const editor = document.getElementById('editor-container');
  if (!editor) return;
  editor.addEventListener('input', () => {
    if (hasOpenDocument()) {
      markDirty();
      const state = getDocState();
      const content = getEditorText();
      if (typeof SyncManager !== 'undefined') {
        SyncManager.queueChange(state.currentDocumentId, content);
      }
    }
  });
}

/* ── Autosave Removed (Handled by SyncManager) ── */

/* ── Load & render list ── */

async function _loadAndRenderList() {
  const listEl = document.getElementById('docs-list');
  if (!listEl) return;

  const isAuthenticated = window.__bayanAuth &&
    window.__bayanAuth.userId &&
    !window.__bayanAuth.isOfflineMode;

  console.log('[DEBUG_AUTH]', JSON.stringify(window.__bayanAuth));

  if (!isAuthenticated) {
    listEl.innerHTML = `
      <div class="docs-signin-prompt">
        <p class="docs-signin-text">سجّل دخولك لحفظ مستنداتك في السحابة</p>
        <button class="btn-primary docs-signin-btn" onclick="linkGoogle()" type="button">
          الدخول بـ Google
        </button>
      </div>`;
    return;
  }

  listEl.innerHTML = `<div class="docs-loading">جاري التحميل...</div>`;
  const docs = await loadDocuments();

  if (!docs.length) {
    listEl.innerHTML = `
      <div class="empty-state">
        <div class="empty-state__icon">
          <svg width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
        </div>
        <div class="empty-state__title">\u0644\u0627 \u062a\u0648\u062c\u062f \u0645\u0633\u062a\u0646\u062f\u0627\u062a \u0628\u0639\u062f</div>
        <div class="empty-state__subtitle">\u0623\u0646\u0634\u0626 \u0645\u0633\u062a\u0646\u062f\u064b\u0627 \u062c\u062f\u064a\u062f\u064b\u0627 \u0644\u0628\u062f\u0621 \u0627\u0644\u0643\u062a\u0627\u0628\u0629</div>
      </div>`;
    return;
  }

  const state = getDocState();
  listEl.innerHTML = docs.map(doc => _buildDocItemHTML(doc, doc.id === state.currentDocumentId)).join('');
  _bindDocItemEvents(listEl);
}

function _buildDocItemHTML(doc, isActive) {
  const date = new Date(doc.updated_at).toLocaleDateString('ar-EG', {
    month: 'short', day: 'numeric'
  });
  return `
    <div class="doc-list-item${isActive ? ' doc-list-item--active' : ''}" data-doc-id="${doc.id}" role="listitem">
      <button class="doc-list-item__open" data-doc-id="${doc.id}" aria-label="فتح ${_escapeAttr(doc.title)}" type="button">
        <span class="doc-list-item__icon" aria-hidden="true">📄</span>
        <span class="doc-list-item__title">${_escapeHtml(doc.title)}</span>
        <span class="doc-list-item__date">${date}</span>
      </button>
      <div class="doc-list-item__actions">
        <button class="doc-list-item__action doc-rename-btn" data-doc-id="${doc.id}" data-doc-title="${_escapeAttr(doc.title)}" aria-label="إعادة تسمية" title="إعادة تسمية" type="button">✎</button>
        <button class="doc-list-item__action doc-delete-btn" data-doc-id="${doc.id}" data-doc-title="${_escapeAttr(doc.title)}" aria-label="حذف" title="حذف" type="button">✕</button>
      </div>
    </div>`;
}

function _bindDocItemEvents(container) {
  container.querySelectorAll('.doc-list-item__open').forEach(btn => {
    btn.addEventListener('click', () => _openDocument(btn.dataset.docId));
  });
  container.querySelectorAll('.doc-rename-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.stopPropagation();
      _startRename(btn.dataset.docId, btn.dataset.docTitle);
    });
  });
  container.querySelectorAll('.doc-delete-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.stopPropagation();
      _confirmDelete(btn.dataset.docId, btn.dataset.docTitle);
    });
  });
}

/* ── Open document ── */

async function _openDocument(id) {
  const doc = await loadDocument(id);
  if (!doc) {
    if (typeof showDocToast === 'function') showDocToast('تعذّر تحميل المستند', 'error');
    return;
  }

  let contentToLoad = doc.content;
  if (typeof SyncManager !== 'undefined') {
    contentToLoad = await SyncManager.loadAndResolveDocument(id);
    if (contentToLoad === null) return;
  }

  loadDocumentText(contentToLoad, { analyze: true });
  setDocState({
    currentDocumentId: doc.id,
    currentDocumentTitle: doc.title,
    hasUnsavedChanges: false
  });
  _updateTitleBar();
  _refreshActiveItem(id);

  // Navigate to editor
  if (typeof showPage === 'function') showPage('editor');

  // Close sidebar on mobile
  const sidebar = document.getElementById('docs-sidebar');
  if (sidebar && window.innerWidth < 1024) {
    sidebar.classList.remove('is-open');
  }
}

/* ── Create document ── */

async function _createNewDocument() {
  const isAuthenticated = window.__bayanAuth &&
    window.__bayanAuth.userId &&
    !window.__bayanAuth.isOfflineMode;
  if (!isAuthenticated) {
    if (typeof showDocToast === 'function') showDocToast('سجّل دخولك لحفظ المستندات', 'info');
    return;
  }

  const titleInput = prompt('اسم المستند الجديد:', 'مستند جديد');
  if (titleInput === null) return; // User pressed Cancel
  const title = titleInput.trim() || 'مستند جديد';
  const doc = await createDocument(title, '');
  if (!doc) {
    if (typeof showDocToast === 'function') showDocToast('تعذّر إنشاء المستند', 'error');
    return;
  }

  // Clear the editor for the new empty document
  loadDocumentText('', { analyze: false });
  setDocState({
    currentDocumentId: doc.id,
    currentDocumentTitle: doc.title,
    hasUnsavedChanges: false
  });
  _updateTitleBar();
  await _loadAndRenderList();
  if (typeof showDocToast === 'function') showDocToast('تم إنشاء المستند ✓', 'success');
}

/* ── Save current document manually ── */

async function saveCurrentDocument() {
  const state = getDocState();
  if (!state.currentDocumentId) {
    await _createNewDocument();
    return;
  }

  const content = getEditorText();
  if (typeof SyncManager !== 'undefined') {
    SyncManager.queueChange(state.currentDocumentId, content);
    await SyncManager.syncNow();
    if (typeof showDocToast === 'function') showDocToast('تم الحفظ ✓', 'success');
  } else {
    const ok = await saveDocument(state.currentDocumentId, content);
    if (ok) {
      markClean();
      _updateTitleBar();
      await _loadAndRenderList();
      if (typeof showDocToast === 'function') showDocToast('تم الحفظ ✓', 'success');
    } else {
      if (typeof showDocToast === 'function') showDocToast('تعذّر الحفظ', 'error');
    }
  }
}

/* ── Rename ── */

function _startRename(id, currentTitle) {
  const newTitle = prompt('الاسم الجديد للمستند:', currentTitle);
  if (!newTitle || newTitle === currentTitle) return;
  _doRename(id, newTitle);
}

async function _doRename(id, newTitle) {
  const ok = await renameDocument(id, newTitle);
  if (!ok) {
    if (typeof showDocToast === 'function') showDocToast('تعذّر إعادة التسمية', 'error');
    return;
  }
  const state = getDocState();
  if (state.currentDocumentId === id) {
    setDocState({ currentDocumentTitle: newTitle });
    _updateTitleBar();
  }
  await _loadAndRenderList();
}

/* ── Delete ── */

async function _confirmDelete(id, title) {
  if (typeof showConfirmDialog === 'function') {
    showConfirmDialog(
      '\u062d\u0630\u0641 \u0627\u0644\u0645\u0633\u062a\u0646\u062f',
      '\u0647\u0644 \u062a\u0631\u064a\u062f \u062d\u0630\u0641 "' + title + '"\u061f \u0644\u0627 \u064a\u0645\u0643\u0646 \u0627\u0644\u062a\u0631\u0627\u062c\u0639 \u0639\u0646 \u0647\u0630\u0627 \u0627\u0644\u0625\u062c\u0631\u0627\u0621.',
      function() { _doDelete(id); }
    );
  } else {
    if (!confirm('\u0647\u0644 \u062a\u0631\u064a\u062f \u062d\u0630\u0641 "' + title + '"\u061f \u0644\u0627 \u064a\u0645\u0643\u0646 \u0627\u0644\u062a\u0631\u0627\u062c\u0639 \u0639\u0646 \u0647\u0630\u0627 \u0627\u0644\u0625\u062c\u0631\u0627\u0621.')) return;
    _doDelete(id);
  }
}

async function _doDelete(id) {
  const ok = await deleteDocument(id);
  if (!ok) {
    if (typeof showDocToast === 'function') showDocToast('\u062a\u0639\u0630\u0651\u0631 \u0627\u0644\u062d\u0630\u0641', 'error');
    return;
  }

  const state = getDocState();
  if (state.currentDocumentId === id) {
    setDocState({ currentDocumentId: null, currentDocumentTitle: '\u0645\u0633\u062a\u0646\u062f \u062c\u062f\u064a\u062f', hasUnsavedChanges: false });
    _updateTitleBar();
  }
  await _loadAndRenderList();
  if (typeof showDocToast === 'function') showDocToast('\u062a\u0645 \u062d\u0630\u0641 \u0627\u0644\u0645\u0633\u062a\u0646\u062f', 'success');
}

/* ── Title bar ── */

function _updateTitleBar() {
  const titleEl = document.getElementById('doc-current-title');
  const saveBtn = document.getElementById('doc-save-btn');
  if (!titleEl) return;

  const state = getDocState();
  titleEl.textContent = state.currentDocumentTitle;

  if (saveBtn) {
    const unsaved = state.hasUnsavedChanges && state.currentDocumentId;
    saveBtn.classList.toggle('doc-save-btn--dirty', !!unsaved);
    const isTempState = saveBtn.classList.contains('is-saving') || saveBtn.classList.contains('is-saved');
    if (!isTempState) {
      saveBtn.title = unsaved ? 'حفظ (يوجد تغييرات غير محفوظة)' : 'حفظ';
    }
  }
}

/* ── Refresh active item in list without full reload ── */

function _refreshActiveItem(activeId) {
  document.querySelectorAll('.doc-list-item').forEach(el => {
    el.classList.toggle('doc-list-item--active', el.dataset.docId === activeId);
  });
}

/* ── Render sidebar HTML into DOM ── */

function _renderSidebar() {
  // The sidebar div is already in HTML — just wire the new-doc button
  const newDocBtn = document.getElementById('docs-new-btn');
  if (newDocBtn) {
    newDocBtn.addEventListener('click', _createNewDocument);
  }

  const saveBtn = document.getElementById('doc-save-btn');
  if (saveBtn) {
    saveBtn.addEventListener('click', saveCurrentDocument);
  }
}

/* ── Helpers ── */

function _escapeHtml(str) {
  return String(str || '')
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');
}

function _escapeAttr(str) {
  return String(str || '').replace(/"/g, '&quot;').replace(/'/g, '&#039;');
}