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
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426


import { useState, useEffect, useCallback, useRef } from 'react';
import { collection, query, where, onSnapshot, doc, getDoc, writeBatch, arrayUnion, deleteDoc, updateDoc, arrayRemove, deleteField } from 'firebase/firestore';
import { ref, set, update, push, serverTimestamp, remove } from 'firebase/database';
import { cryptoService } from '@/lib/crypto-service';
import type { User, Group, GroupInvitation, GroupType, Contact, GroupSendingMode, ChatRecipient } from '@/lib/types';
import { useAuth } from '@/contexts/auth-context';
import { useFirebase } from '@/contexts/firebase-context';
import { useSettings } from '@/contexts/settings-context';
import { useContacts } from '@/contexts/contacts-context';
import { storageService } from '@/lib/storage-service';

interface UseGroupsProps {
    setRecipient: (recipient: ChatRecipient | null | ((prev: ChatRecipient | null) => ChatRecipient | null)) => void;
}

export const useGroupsCore = ({ setRecipient }: UseGroupsProps) => {
    const { currentUser } = useAuth();
    const { db, rtdb } = useFirebase();
    const { contacts } = useContacts();
    const { addToast, playSound, t } = useSettings();
    
    const [groups, setGroups] = useState<Group[]>([]);
    const [groupInvitations, setGroupInvitations] = useState<GroupInvitation[]>([]);
    const previousGroupsRef = useRef<Group[]>([]);


    useEffect(() => {
        if (!currentUser) {
            setGroups([]);
            setGroupInvitations([]);
            return;
        }

        let isMounted = true;
        
        // Load cached groups first
        storageService.getGroups().then(cachedGroups => {
            if (isMounted && cachedGroups.length > 0) {
                const sortedGroups = cachedGroups.sort((a, b) => a.info.name.localeCompare(b.info.name));
                setGroups(sortedGroups);
                previousGroupsRef.current = sortedGroups;
            }
        });

        const groupsQuery = query(collection(db, 'groups'), where(`members.${currentUser.uid}`, '==', true));
        const groupsUnsub = onSnapshot(groupsQuery, (snapshot) => {
            const fetchedGroups = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() } as Group));
            const sortedGroups = fetchedGroups.sort((a, b) => a.info.name.localeCompare(b.info.name));
            
            const prevGroupIds = new Set(previousGroupsRef.current.map(g => g.id));
            const currentGroupIds = new Set(sortedGroups.map(g => g.id));

            prevGroupIds.forEach(id => {
                if (!currentGroupIds.has(id)) {
                    setRecipient(prevRecipient => {
                        if (prevRecipient && prevRecipient.uid === id) {
                            addToast(t('You have been removed from the group.'));
                            return null;
                        }
                        return prevRecipient;
                    });
                }
            });
            
            if (isMounted) {
                setGroups(sortedGroups);
                storageService.saveGroups(sortedGroups);
            }
            previousGroupsRef.current = sortedGroups;
        });

        const invitationsUnsub = onSnapshot(collection(db, 'users', currentUser.uid, 'groupInvitations'), (snapshot) => {
            if (isMounted) {
                setGroupInvitations(snapshot.docs.map(doc => doc.data() as GroupInvitation));
            }
        });

        return () => {
            isMounted = false;
            groupsUnsub();
            invitationsUnsub();
        };
    }, [currentUser, db, setRecipient, addToast, t]);

    const resetGroupKeys = useCallback(async (groupId: string, newMemberUids?: string[]) => {
        if (!currentUser) throw new Error("Current user not found for key reset.");
    
        try {
            cryptoService.clearGroupKeyCache(groupId);
    
            const groupRef = doc(db, 'groups', groupId);
            const groupSnap = await getDoc(groupRef);
            if (!groupSnap.exists()) throw new Error("Group not found for key reset.");
    
            const groupData = groupSnap.data() as Group;
            const finalMemberUids = newMemberUids || Object.keys(groupData.members);
    
            if (finalMemberUids.length === 0) {
                await updateDoc(groupRef, { encryptedKeys: {}, keyLastRotatedAt: Date.now() });
                return;
            }
    
            const { encryptedKeys, groupKeyString } = await cryptoService.createEncryptedGroupKey(finalMemberUids, rtdb);
            
            const newKeyVersion = Date.now();

            if (finalMemberUids.includes(currentUser.uid)) {
                 cryptoService.storeGroupKey(groupId, newKeyVersion, groupKeyString);
            }
           
            await updateDoc(groupRef, { encryptedKeys: encryptedKeys, keyLastRotatedAt: newKeyVersion });
    
            await push(ref(rtdb, `chats/${groupId}/messages`), {
                sender: 'system',
                text: t('systemKeyReset'),
                timestamp: serverTimestamp(),
                isSystemMessage: true,
            });
    
            addToast(t('groupKeyResetSuccess'), { variant: "default" });
    
        } catch (error) {
            console.error("Failed to reset group keys:", error);
            addToast(t('groupKeyResetError'), { variant: "destructive" });
            throw error;
        }
    }, [currentUser, rtdb, db, addToast, t]);

    const createGroup = useCallback(async (name: string, photoURL: string, memberUids: string[], groupType: GroupType) => {
        if (!currentUser) return;
        
        try {
            const newGroupRef = doc(collection(db, 'groups'));
            const groupId = newGroupRef.id;
            
            const defaultPhoto = `https://api.dicebear.com/8.x/identicon/svg?seed=${name}`;
            const allMemberUids = [currentUser.uid, ...memberUids];
            
            const { encryptedKeys, groupKeyString } = await cryptoService.createEncryptedGroupKey(allMemberUids, rtdb);
            const keyVersion = Date.now();
            cryptoService.storeGroupKey(groupId, keyVersion, groupKeyString);
            
            const groupData: Omit<Group, 'id'> = {
                info: {
                    name,
                    photoURL: photoURL || defaultPhoto,
                    createdBy: currentUser.uid,
                    createdAt: Date.now(),
                    type: groupType,
                    settings: { sendingMode: 'everyone' }
                },
                members: { [currentUser.uid]: true, ...Object.fromEntries(memberUids.map(uid => [uid, true])) },
                admins: { [currentUser.uid]: true },
                encryptedKeys: encryptedKeys,
                keyLastRotatedAt: keyVersion,
            };

            const batch = writeBatch(db);
            batch.set(newGroupRef, groupData);

            allMemberUids.forEach(uid => {
                 batch.update(doc(db, 'users', uid), { groups: arrayUnion(groupId) });
            })

            await batch.commit();
            
            const participantsForRtdb = Object.fromEntries(allMemberUids.map(uid => [uid, true]));
            await set(ref(rtdb, `chats/${groupId}/participants`), participantsForRtdb);

            addToast(t('groupCreated', { name }));
        } catch (error: any) {
            addToast(t('groupCreateError', { error: error.message }), { variant: 'destructive' });
            console.error(error);
        }
    }, [currentUser, addToast, db, rtdb, t]);

    const acceptGroupInvitation = async (invitation: GroupInvitation) => {
        if (!currentUser) return;
        try {
            const groupDoc = await getDoc(doc(db, 'groups', invitation.groupId));
            if (!groupDoc.exists()) throw new Error("Group does not exist.");

            const batch = writeBatch(db);
            batch.update(doc(db, 'groups', invitation.groupId), { [`members.${currentUser.uid}`]: true });
            batch.update(doc(db, 'users', currentUser.uid), { groups: arrayUnion(invitation.groupId) });
            batch.delete(doc(db, 'users', currentUser.uid, 'groupInvitations', invitation.groupId));
            
            await batch.commit();

            await set(ref(rtdb, `chats/${invitation.groupId}/participants/${currentUser.uid}`), true);
            
            await push(ref(rtdb, `chats/${invitation.groupId}/messages`), {
                sender: 'system',
                text: t('systemUserJoined', { name: currentUser.displayName }),
                timestamp: serverTimestamp(),
                isSystemMessage: true,
            });

            addToast(t('joinedGroup', { name: invitation.groupName }));
        } catch (error) {
            console.error("Error accepting group invitation:", error);
            addToast(t('joinGroupError'), { variant: 'destructive' });
        }
    };
    
    const declineGroupInvitation = async (invitation: GroupInvitation) => {
         if (!currentUser) return;
         try {
             await deleteDoc(doc(db, 'users', currentUser.uid, 'groupInvitations', invitation.groupId));
             addToast(t('invitationDeclined'));
         } catch(error) {
             console.error("Error declining group invitation:", error);
             addToast(t('declineInvitationError'), { variant: "destructive" });
         }
    };

    const updateGroupInfo = useCallback(async (groupId: string, newInfo: { name?: string; photoURL?: string; description?: string; }) => {
        const groupRef = doc(db, 'groups', groupId);
        const updates: { [key: string]: any } = {};
        if (newInfo.name) updates['info.name'] = newInfo.name;
        if (newInfo.photoURL) updates['info.photoURL'] = newInfo.photoURL;
        if (newInfo.description !== undefined) updates['info.description'] = newInfo.description;
        
        await updateDoc(groupRef, updates);
        addToast(t('groupInfoUpdated'));
    }, [addToast, db, t]);
    
    const leaveGroup = useCallback(async (groupId: string) => {
        if (!currentUser) return;
        try {
            const groupRef = doc(db, 'groups', groupId);
            const groupSnap = await getDoc(groupRef);
            if (!groupSnap.exists()) return;
            const groupData = groupSnap.data() as Group;
            const remainingMembers = Object.keys(groupData.members).filter(uid => uid !== currentUser.uid);

            const batch = writeBatch(db);
            batch.update(groupRef, {
                [`members.${currentUser.uid}`]: deleteField(),
                [`admins.${currentUser.uid}`]: deleteField(),
                [`encryptedKeys.${currentUser.uid}`]: deleteField(),
            });
            batch.update(doc(db, 'users', currentUser.uid), {
                groups: arrayRemove(groupId)
            });
            await batch.commit();

            await remove(ref(rtdb, `chats/${groupId}/participants/${currentUser.uid}`));

            await push(ref(rtdb, `chats/${groupId}/messages`), {
                sender: 'system',
                text: t('systemUserLeft', { name: currentUser.displayName }),
                timestamp: serverTimestamp(),
                isSystemMessage: true,
            });
            
            await resetGroupKeys(groupId, remainingMembers);
            
            addToast(t('leftGroup'));
            setRecipient(null);

        } catch (error) {
            console.error("Error leaving group:", error);
            addToast(t('leaveGroupError'), { variant: 'destructive' });
        }
    }, [currentUser, addToast, db, rtdb, resetGroupKeys, t, setRecipient]);

    const removeMemberFromGroup = useCallback(async (groupId: string, memberUid: string, memberName: string) => {
        if (!currentUser) return;
        try {
            const groupRef = doc(db, 'groups', groupId);
            const groupSnap = await getDoc(groupRef);
            if (!groupSnap.exists()) return;
            const groupData = groupSnap.data() as Group;
            const remainingMembers = Object.keys(groupData.members).filter(uid => uid !== memberUid);
            
            const batch = writeBatch(db);
            batch.update(groupRef, {
                [`members.${memberUid}`]: deleteField(),
                [`admins.${memberUid}`]: deleteField(),
                [`encryptedKeys.${memberUid}`]: deleteField(),
            });
            batch.update(doc(db, 'users', memberUid), {
                groups: arrayRemove(groupId)
            });
            await batch.commit();
            
            await remove(ref(rtdb, `chats/${groupId}/participants/${memberUid}`));

            await push(ref(rtdb, `chats/${groupId}/messages`), {
                sender: 'system',
                text: t('systemUserRemoved', { user: memberName, admin: currentUser.displayName }),
                timestamp: serverTimestamp(),
                isSystemMessage: true,
            });
            
            await resetGroupKeys(groupId, remainingMembers);

            addToast(t('memberRemoved', { name: memberName }));
        } catch (error) {
            console.error("Error removing member:", error);
            addToast(t('removeMemberError'), { variant: 'destructive' });
        }
    }, [currentUser, addToast, db, rtdb, resetGroupKeys, t]);

    const addMembersToGroup = useCallback(async (groupId: string, newMemberUids: string[]) => {
        if (!currentUser) return;
    
        try {
            const groupRef = doc(db, 'groups', groupId);
            const groupSnap = await getDoc(groupRef);
            if (!groupSnap.exists()) throw new Error("Group not found.");
            
            const groupData = groupSnap.data() as Group;
    
            if (!groupData.admins[currentUser.uid]) {
                addToast(t('adminsOnlyAction'), { variant: 'destructive' });
                return;
            }
    
            const membersToAdd = newMemberUids.filter(uid => !groupData.members[uid]);
            if (membersToAdd.length === 0) {
                addToast(t('allMembersAlreadyInGroup'), { variant: "default" });
                return;
            }
    
            const batch = writeBatch(db);
            const memberUpdates: { [key: string]: any } = {};
            const participantUpdates: { [key: string]: true } = {};
            
            membersToAdd.forEach(uid => {
                memberUpdates[`members.${uid}`] = true;
                participantUpdates[uid] = true;
                batch.update(doc(db, 'users', uid), { groups: arrayUnion(groupId) });
            });
    
            batch.update(groupRef, memberUpdates);
            await batch.commit();
    
            await update(ref(rtdb, `chats/${groupId}/participants`), participantUpdates);

            const updatedGroupSnap = await getDoc(groupRef);
            if (!updatedGroupSnap.exists()) throw new Error("Group disappeared after member update.");
            const updatedGroupData = updatedGroupSnap.data() as Group;
            const finalMemberUids = Object.keys(updatedGroupData.members);
    
            await resetGroupKeys(groupId, finalMemberUids);
    
            const addedContacts = contacts.filter(c => membersToAdd.includes(c.uid)).map(c => c.name).join(', ');
            await push(ref(rtdb, `chats/${groupId}/messages`), {
                sender: 'system',
                text: t('systemUserAdded', { admin: currentUser.displayName, users: addedContacts }),
                timestamp: serverTimestamp(),
                isSystemMessage: true,
            });
    
            addToast(t('membersAdded', { count: membersToAdd.length }));
    
        } catch (error) {
            console.error("Failed to add members:", error);
            addToast(t('addMembersError'), { variant: 'destructive' });
        }
    }, [currentUser, contacts, addToast, db, rtdb, resetGroupKeys, t]);

    const toggleGroupAdmin = useCallback(async (groupId: string, memberUid: string, isCurrentlyAdmin: boolean) => {
        const groupRef = doc(db, 'groups', groupId);
        if (isCurrentlyAdmin) {
            await updateDoc(groupRef, { [`admins.${memberUid}`]: deleteField() });
            addToast(t('demotedToMember'));
        } else {
            await updateDoc(groupRef, { [`admins.${memberUid}`]: true });
            addToast(t('promotedToAdmin'));
        }
    }, [addToast, db, t]);

    const updateGroupSendingMode = useCallback(async (groupId: string, mode: GroupSendingMode) => {
         const groupRef = doc(db, 'groups', groupId);
         await updateDoc(groupRef, { 'info.settings.sendingMode': mode });
         addToast(t('groupSettingsUpdated'));
    }, [addToast, db, t]);

    const toggleMuteMember = useCallback(async (groupId: string, memberUid: string, memberName: string, isCurrentlyMuted: boolean) => {
        if (!currentUser) return;
        const groupRef = doc(db, 'groups', groupId);
        const updatePath = `info.mutedMembers.${memberUid}`;
        const systemMessageText = isCurrentlyMuted 
            ? t('systemUnmuted', { user: memberName, admin: currentUser.displayName })
            : t('systemMuted', { user: memberName, admin: currentUser.displayName });
        
        if (isCurrentlyMuted) {
            await updateDoc(groupRef, { [updatePath]: deleteField() });
        } else {
            await updateDoc(groupRef, { [updatePath]: true });
        }
        
        await push(ref(rtdb, `chats/${groupId}/messages`), {
            sender: 'system',
            text: systemMessageText,
            timestamp: serverTimestamp(),
            isSystemMessage: true,
        });

        addToast(isCurrentlyMuted ? t('memberUnmuted', { name: memberName }) : t('memberMuted', { name: memberName }));
        
    }, [addToast, db, currentUser, rtdb, t]);


    return {
        groups,
        groupInvitations,
        createGroup,
        acceptGroupInvitation,
        declineGroupInvitation,
        updateGroupInfo,
        addMembersToGroup,
        removeMemberFromGroup,
        leaveGroup,
        toggleGroupAdmin,
        updateGroupSendingMode,
        toggleMuteMember,
        resetGroupKeys
    };
};