-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfriend-invite.js
More file actions
342 lines (316 loc) · 14.3 KB
/
Copy pathfriend-invite.js
File metadata and controls
342 lines (316 loc) · 14.3 KB
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
// ============================================================
// EL JASUS — FRIEND INVITE SYSTEM v1.0
// Global script: include on ALL pages.
// Shows incoming room invites as a persistent notification
// with Accept / Decline buttons and a 5-minute countdown.
// ============================================================
(function () {
'use strict';
const FIREBASE_CONFIG = {
apiKey: 'AIzaSyDnd-pmKEatI3DaFz6xHWB5ucurtHXt9tk',
authDomain: 'el-jasus.firebaseapp.com',
databaseURL: 'https://el-jasus-default-rtdb.asia-southeast1.firebasedatabase.app',
projectId: 'el-jasus',
storageBucket: 'el-jasus.firebasestorage.app',
messagingSenderId: '415659587906',
appId: '1:415659587906:web:782f7940176ea4097eb0db',
};
const INVITE_TTL = 5 * 60 * 1000; // 5 minutes
// ── CSS injection ──────────────────────────────────────────
const css = `
#fi-container {
position: fixed; bottom: 80px; left: 50%;
transform: translateX(-50%);
z-index: 10500;
display: flex; flex-direction: column; gap: 10px;
align-items: center; pointer-events: none;
width: min(420px, 94vw);
}
.fi-toast {
width: 100%;
background: linear-gradient(135deg, rgba(10,14,26,.97), rgba(20,25,45,.97));
border: 2px solid rgba(0,242,255,.45);
border-radius: 20px;
padding: 16px 18px;
font-family: 'Cairo', sans-serif;
box-shadow: 0 8px 32px rgba(0,0,0,.55), 0 0 24px rgba(0,242,255,.15);
backdrop-filter: blur(20px);
pointer-events: all;
animation: fi-slideIn .35s cubic-bezier(.4,0,.2,1);
direction: rtl;
}
.fi-toast.fi-leaving {
animation: fi-slideOut .3s ease forwards;
}
@keyframes fi-slideIn {
from { opacity:0; transform:translateY(18px) scale(.96); }
to { opacity:1; transform:translateY(0) scale(1); }
}
@keyframes fi-slideOut {
to { opacity:0; transform:translateY(18px) scale(.95); }
}
.fi-header {
display: flex; align-items: center; gap: 10px; margin-bottom: 10px;
}
.fi-avatar {
width: 40px; height: 40px; border-radius: 50%; flex-shrink: 0;
background: linear-gradient(135deg,#00f2ff,#7c30ff);
display: flex; align-items: center; justify-content: center;
font-size: 16px; color: white;
}
.fi-info { flex: 1; }
.fi-title { font-size: 13px; font-weight: 900; color: #fff; }
.fi-sub { font-size: 11px; color: rgba(255,255,255,.55); margin-top: 1px; }
.fi-timer-bar {
height: 3px; border-radius: 2px;
background: rgba(255,255,255,.1);
overflow: hidden; margin-bottom: 12px;
}
.fi-timer-fill {
height: 100%; border-radius: 2px;
background: linear-gradient(90deg,#00f2ff,#7c30ff);
transition: width .5s linear;
}
.fi-timer-fill.fi-urgent { background: linear-gradient(90deg,#f97316,#ef4444); }
.fi-timer-label {
font-size: 10px; color: rgba(255,255,255,.4);
text-align: left; direction: ltr;
margin-bottom: 10px; font-family: 'Orbitron', monospace;
}
.fi-btns { display: flex; gap: 10px; }
.fi-btn {
flex: 1; padding: 10px; border-radius: 12px;
font-family: 'Cairo', sans-serif; font-weight: 900; font-size: 13px;
cursor: pointer; border: 2px solid; transition: all .2s;
}
.fi-btn-accept {
background: rgba(34,197,94,.15); border-color: rgba(34,197,94,.5); color: #22c55e;
}
.fi-btn-accept:hover { background: rgba(34,197,94,.3); }
.fi-btn-decline {
background: rgba(239,68,68,.12); border-color: rgba(239,68,68,.4); color: #ef4444;
}
.fi-btn-decline:hover { background: rgba(239,68,68,.25); }
.fi-btn:disabled { opacity: .5; cursor: not-allowed; }
.fi-waiting-badge {
display: inline-flex; align-items: center; gap: 6px;
padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 700;
background: rgba(251,191,36,.12); border: 1px solid rgba(251,191,36,.35); color: #fbbf24;
margin-bottom: 10px;
}
.fi-pulse { animation: fi-pulse 1.4s ease-in-out infinite; }
@keyframes fi-pulse { 0%,100%{opacity:1;} 50%{opacity:.45;} }
`;
const styleEl = document.createElement('style');
styleEl.textContent = css;
document.head.appendChild(styleEl);
// ── Container ──────────────────────────────────────────────
const container = document.createElement('div');
container.id = 'fi-container';
document.body.appendChild(container);
// ── Active toasts map: inviteKey → { el, timer, interval } ─
const active = {};
// ── Firebase bootstrap ─────────────────────────────────────
let db, auth, currentUser;
let _ref, _update, _remove, _get, _onChildAdded, _onValue, _set;
async function init() {
const { initializeApp, getApps } = await import(
'https://www.gstatic.com/firebasejs/12.7.0/firebase-app.js'
);
const authMod = await import(
'https://www.gstatic.com/firebasejs/12.7.0/firebase-auth.js'
);
const dbMod = await import(
'https://www.gstatic.com/firebasejs/12.7.0/firebase-database.js'
);
const app = getApps().length ? getApps()[0] : initializeApp(FIREBASE_CONFIG);
auth = authMod.getAuth(app);
db = dbMod.getDatabase(app);
_ref = dbMod.ref;
_update = dbMod.update;
_remove = dbMod.remove;
_get = dbMod.get;
_onChildAdded = dbMod.onChildAdded;
_onValue = dbMod.onValue;
_set = dbMod.set;
authMod.onAuthStateChanged(auth, user => {
currentUser = user;
if (user) listenInvites(user.uid);
});
}
// ── Listen for incoming invites ────────────────────────────
function listenInvites(uid) {
const invRef = _ref(db, `invites/${uid}`);
_onChildAdded(invRef, snap => {
const key = snap.key;
const data = snap.val();
if (!data || data.status !== 'pending') return;
if (data.expiresAt < Date.now()) { _remove(_ref(db, `invites/${uid}/${key}`)); return; }
if (!active[key]) showInvite(uid, key, data);
});
}
// ── Show invite toast ──────────────────────────────────────
function showInvite(myUid, key, data) {
const toast = document.createElement('div');
toast.className = 'fi-toast';
toast.innerHTML = `
<div class="fi-header">
<div class="fi-avatar"><i class="fas fa-user-friends"></i></div>
<div class="fi-info">
<div class="fi-title">دعوة من <strong>${data.fromName}</strong></div>
<div class="fi-sub">دعوة للانضمام إلى غرفة اللعب</div>
</div>
</div>
<div class="fi-waiting-badge">
<span class="fi-pulse">●</span>
<span>كود الغرفة: <strong>${data.roomCode}</strong></span>
</div>
<div class="fi-timer-bar">
<div class="fi-timer-fill" id="fi-fill-${key}" style="width:100%;"></div>
</div>
<div class="fi-timer-label" id="fi-label-${key}">5:00</div>
<div class="fi-btns">
<button class="fi-btn fi-btn-accept" id="fi-acc-${key}">✅ قبول</button>
<button class="fi-btn fi-btn-decline" id="fi-dec-${key}">❌ رفض</button>
</div>
`;
container.appendChild(toast);
const total = data.expiresAt - Date.now();
const fill = toast.querySelector(`#fi-fill-${key}`);
const label = toast.querySelector(`#fi-label-${key}`);
// Countdown interval
const interval = setInterval(() => {
const remaining = data.expiresAt - Date.now();
if (remaining <= 0) { dismiss(myUid, key, 'expired'); return; }
const pct = (remaining / INVITE_TTL) * 100;
fill.style.width = pct + '%';
if (pct < 33) fill.classList.add('fi-urgent');
const m = Math.floor(remaining / 60000);
const s = Math.floor((remaining % 60000) / 1000);
label.textContent = `${m}:${s.toString().padStart(2,'0')}`;
}, 500);
// Buttons
toast.querySelector(`#fi-acc-${key}`).onclick = () => acceptInvite(myUid, key, data);
toast.querySelector(`#fi-dec-${key}`).onclick = () => dismiss(myUid, key, 'declined');
active[key] = { el: toast, interval };
}
// ── Accept invite ──────────────────────────────────────────
async function acceptInvite(myUid, key, data) {
const accBtn = document.getElementById(`fi-acc-${key}`);
const decBtn = document.getElementById(`fi-dec-${key}`);
if (accBtn) { accBtn.disabled = true; accBtn.textContent = '...'; }
if (decBtn) decBtn.disabled = true;
try {
const roomSnap = await _get(_ref(db, `rooms/${data.roomCode}`));
if (!roomSnap.exists()) {
showBanner('❌ الغرفة لم تعد موجودة', 'error');
dismiss(myUid, key, 'expired');
return;
}
const room = roomSnap.val();
if (room.status === 'waiting') {
// Join directly
const players = Array.isArray(room.players) ? room.players : Object.values(room.players || {});
const myName = currentUser.displayName || localStorage.getItem('eljasus_user_name') || 'لاعب';
if (!players.includes(myName)) {
if (players.length >= 10) { showBanner('❌ الغرفة ممتلئة', 'error'); dismiss(myUid, key, 'expired'); return; }
await _update(_ref(db, `rooms/${data.roomCode}`), { players: [...players, myName] });
}
localStorage.setItem('currentRoom', data.roomCode);
localStorage.setItem('isHost', 'false');
await _update(_ref(db, `invites/${myUid}/${key}`), { status: 'accepted' });
dismiss(myUid, key, null, true);
window.location.href = 'room.html';
} else {
// Game in progress — notify and wait
const phaseLabel = {
playing: 'جارٍ تقديم الأدوار',
discussion: 'مرحلة النقاش',
voting: 'مرحلة التصويت',
reveal: 'مرحلة الكشف',
}[room.status] || room.status;
showBanner(`⏳ الغرفة الآن في مرحلة "${phaseLabel}" — ستنضم تلقائياً عند انتهاء الجولة`, 'warning', 6000);
// Store pending join
localStorage.setItem('fi_pending_room', data.roomCode);
localStorage.setItem('fi_pending_name', data.fromName);
await _update(_ref(db, `invites/${myUid}/${key}`), { status: 'accepted' });
dismiss(myUid, key, null, true);
watchRoomForWaiting(data.roomCode);
}
} catch (e) {
showBanner('❌ خطأ: ' + e.message, 'error');
if (accBtn) { accBtn.disabled = false; accBtn.textContent = '✅ قبول'; }
if (decBtn) decBtn.disabled = false;
}
}
// ── Watch room until it goes back to 'waiting' ─────────────
function watchRoomForWaiting(roomCode) {
let unsubscribe;
const unsub = _onValue(_ref(db, `rooms/${roomCode}/status`), snap => {
if (snap.val() === 'waiting') {
showBanner(`✅ انتهت الجولة في غرفة ${roomCode} — يمكنك الانضمام الآن!`, 'success', 8000);
localStorage.setItem('currentRoom', roomCode);
localStorage.setItem('isHost', 'false');
// Small delay for user to notice
setTimeout(() => { window.location.href = 'room.html'; }, 2500);
if (unsubscribe) unsubscribe();
}
});
unsubscribe = unsub;
}
// ── Dismiss toast ──────────────────────────────────────────
function dismiss(myUid, key, status, skipDb = false) {
const entry = active[key];
if (!entry) return;
clearInterval(entry.interval);
entry.el.classList.add('fi-leaving');
setTimeout(() => { entry.el.remove(); delete active[key]; }, 310);
if (!skipDb && status) {
_update(_ref(db, `invites/${myUid}/${key}`), { status }).catch(() => {});
}
}
// ── Simple top banner ──────────────────────────────────────
function showBanner(msg, type = 'info', duration = 4500) {
const colors = {
success: 'rgba(34,197,94,.18);border-color:rgba(34,197,94,.5);color:#22c55e',
warning: 'rgba(251,191,36,.14);border-color:rgba(251,191,36,.5);color:#fbbf24',
error: 'rgba(239,68,68,.15);border-color:rgba(239,68,68,.5);color:#ef4444',
info: 'rgba(0,242,255,.1);border-color:rgba(0,242,255,.4);color:#00f2ff',
};
const b = document.createElement('div');
b.style.cssText = `position:fixed;top:12px;left:50%;transform:translateX(-50%);
z-index:10600;padding:13px 28px;border-radius:16px;font-family:'Cairo',sans-serif;
font-weight:700;font-size:13px;text-align:center;backdrop-filter:blur(14px);
background:${colors[type] || colors.info};border:2px solid;
box-shadow:0 8px 28px rgba(0,0,0,.45);direction:rtl;min-width:280px;`;
b.textContent = msg;
document.body.appendChild(b);
setTimeout(() => { b.style.opacity='0'; b.style.transition='opacity .4s'; setTimeout(()=>b.remove(),420); }, duration);
}
// ── Public API ─────────────────────────────────────────────
// Called by friends.html invite button
window.FI = {
/**
* Send a room invite to a friend.
* @param {string} friendUid
* @param {string} friendName
* @param {string} roomCode
* @param {string} fromName - sender's display name
*/
async sendInvite(friendUid, friendName, roomCode, fromName) {
if (!db || !currentUser) throw new Error('Firebase not ready');
const invRef = _ref(db, `invites/${friendUid}`);
const { push } = await import('https://www.gstatic.com/firebasejs/12.7.0/firebase-database.js');
await push(invRef, {
fromUid: currentUser.uid,
fromName: fromName || currentUser.displayName || 'لاعب',
roomCode,
timestamp: Date.now(),
expiresAt: Date.now() + INVITE_TTL,
status: 'pending',
});
},
showBanner,
};
init().catch(console.error);
})();