/**
 * ============================================================
 * 🏗️ GroupManagerService.js
 * High-level service wrapping WPP group modules for the
 * "Group Management" UI tab.
 *
 * Runs in PAGE CONTEXT (injected via content.js like sender.js)
 * Communicates with panel.js via window.postMessage
 *
 * Dependencies:
 *   - WPP engine (wa.js → window.WPP/WPPMP/WPPConnect)
 *   - Humanizer engine (humanizer.js → window.Humanizer)
 *
 * Modules referenced (from group_functions_extracted_v2.js):
 *   [20292] WPP.group.create(title, participants[], parentGroupId?)
 *   [7103]  WPP.group.addParticipants(groupId, participantIds[])
 *   Response codes: 200=OK, 403=Privacy, 409=Already, 421=Pending
 * ============================================================
 */

(function () {
    'use strict';

    const sleep = (ms) => new Promise(r => setTimeout(r, ms));

    const withTimeout = (promise, ms, timeoutErrorMsg) => {
        return Promise.race([
            promise,
            new Promise((_, reject) => setTimeout(() => reject(new Error(timeoutErrorMsg)), ms))
        ]);
    };

    // ============================================================
    // WPP Engine Reference
    // ============================================================
    function getWPP() {
        return window.WPP || window.WPPMP || window.WPPConnect;
    }

    async function ensureWPPReady() {
        const wpp = getWPP();
        if (wpp && wpp.isReady) return wpp;
        for (let i = 0; i < 60; i++) {
            await sleep(500);
            const retry = getWPP();
            if (retry && retry.isReady) return retry;
        }
        throw new Error('WPP Engine not ready after 30s');
    }

    // ============================================================
    // Humanizer Delay for Group Operations
    // ============================================================
    function getHumanizerDelay(batchIndex) {
        const H = window.Humanizer;
        if (H && H.DelayEngine) {
            const result = H.DelayEngine.calculate(
                1000,                    // base delay 8s
                2000,                 // typing time placeholder
                batchIndex,           // sent count for fatigue
                0                     // no errors yet
            );
            return result.finalDelayMs;
        }
        // Fallback: random 5–15s
        return Math.floor(Math.random() * 10000) + 5000;
    }


    // ============================================================
    // Progress Reporter
    // ============================================================
    function emitProgress(data) {
        window.postMessage({
            type: 'GM_PROGRESS',
            ...data
        }, '*');
    }

    // ============================================================
    // GroupManagerService
    // ============================================================
    const GroupManagerService = {

        // ----------------------------------------------------------
        // getManagedGroups()
        // Returns only groups where current user is Admin/SuperAdmin
        // ----------------------------------------------------------
        getManagedGroups: async function () {
            const WPP = await ensureWPPReady();

            const allChats = await WPP.chat.list();
            const groupChats = allChats.filter(c => c.id?.server === 'g.us');

            // Get current user ID for admin check
            const myWid = WPP.conn?.me || WPP.conn?.wid;
            const myId = myWid?._serialized
                || (myWid && typeof myWid.toString === 'function' ? myWid.toString() : '');

            const managedGroups = [];

            for (const chat of groupChats) {
                if (!chat.id?._serialized) continue;
                const groupId = chat.id._serialized;

                // Check if current user is admin/superAdmin in this group
                try {
                    const participants = await WPP.group.getParticipants(groupId);
                    if (!participants || !Array.isArray(participants)) continue;

                    const me = participants.find(p => {
                        const pid = p.id?._serialized
                            || (p.id && typeof p.id.toString === 'function' ? p.id.toString() : '');
                        return pid === myId;
                    });

                    // Skip groups where user is NOT admin or superAdmin
                    if (!me || (!me.isAdmin && !me.isSuperAdmin)) continue;
                } catch (e) {
                    // Failed to fetch metadata for this group — skip silently
                    continue;
                }

                let name = chat.name || chat.formattedTitle;

                // If name is missing, try to fetch it properly
                if (!name) {
                    try {
                        const info = await WPP.chat.get(groupId);
                        if (info?.name) name = info.name;
                    } catch (e) { }
                }

                managedGroups.push({
                    id: groupId,
                    name: name || 'مجموعة'
                });
            }

            return managedGroups;
        },

        // ----------------------------------------------------------
        // createNewGroupFull()
        // Creates group with ALL participants at once → sets
        // description → sets icon → processes member results →
        // sends invites for privacy-blocked → returns full results
        //
        // Wraps: WPP.group.create (module 20292)
        // This matches human behavior: user selects all members
        // then presses create. No loop, no delays between members.
        // ----------------------------------------------------------
        createNewGroupFull: async function ({
            title,
            participants = [],
            description = '',
            base64Image = null,
            sendPermission = 'admin',   // 'admin' | 'all'
            addPermission = 'admin',    // 'admin' | 'all'
            sendInviteOnFail = true
        }) {
            const WPP = await ensureWPPReady();

            if (!title || !title.trim()) {
                throw new Error('Group title is required');
            }

            if (!participants || participants.length === 0) {
                throw new Error('يجب تحديد عضو واحد على الأقل لإنشاء مجموعة في واتساب');
            }

            emitProgress({
                stage: 'creating',
                status: 'active',
                message: 'جاري إنشاء المجموعة...'
            });

            // --- Step 1: Create the group with ALL participants at once ---
            // WPP.group.create accepts title + participants[]
            // Passing all members in one call matches human behavior
            // and avoids rate-overlimit risks from individual addParticipants calls
            const allJids = participants.map(p => p.replace(/\D/g, '') + '@c.us');

            let createResult;
            try {
                createResult = await withTimeout(
                    WPP.group.create(title.trim(), allJids),
                    30000,
                    'Timeout: Group creation did not complete in 30 seconds'
                );
            } catch (e) {
                emitProgress({ stage: 'creating', status: 'error', message: e.message });
                throw e;
            }

            const groupId = createResult.gid?._serialized
                || (createResult.gid && typeof createResult.gid.toString === 'function'
                    ? createResult.gid.toString()
                    : createResult.gid);
            if (!groupId) {
                throw new Error('Group creation failed: no GID returned');
            }

            console.log('✅ Group created with GID:', groupId);

            // --- Process participant results from createResult.participants ---
            const results = {
                total: participants.length,
                success: 0,
                failed: 0,
                alreadyMember: 0,
                pendingApproval: 0,
                privacyBlocked: 0,
                inviteSent: 0,
                errors: [],
                details: {}   // { [phone]: { code, message, invite_code } }
            };

            if (createResult.participants && typeof createResult.participants === 'object') {
                for (const [jid, info] of Object.entries(createResult.participants)) {
                    const phone = jid.replace('@c.us', '');
                    const code = Number(info.code || info.error || -1);
                    const inviteCode = info.invite_code || null;
                    const message = info.message || '';

                    results.details[phone] = { code, message, invite_code: inviteCode };

                    if (code === 200) {
                        results.success++;
                        console.log(`✅ Added during creation: ${phone}`);
                    } else if (code === 403) {
                        results.privacyBlocked++;
                        results.failed++;
                        console.log(`🔒 Privacy blocked: ${phone}`);
                    } else if (code === 409) {
                        results.alreadyMember++;
                        console.log(`ℹ️ Already member: ${phone}`);
                    } else if (code === 421) {
                        results.pendingApproval++;
                        console.log(`⏳ Pending approval: ${phone}`);
                    } else {
                        results.failed++;
                        results.errors.push({ phone, code, message });
                        console.warn(`❌ Failed (${code}): ${phone} - ${message}`);
                    }
                }
            } else {
                // If no participants object returned, assume all were added during creation
                for (const p of participants) {
                    const phone = p.replace(/\D/g, '');
                    results.details[phone] = { code: 200, message: 'Added during creation', invite_code: null };
                    results.success++;
                }
            }

            emitProgress({
                stage: 'creating',
                status: 'done',
                message: `✅ تم إنشاء المجموعة: ${title}`,
                groupId: groupId,
                results: results
            });

            // --- Step 2: Set Description (if provided) ---
            if (description && description.trim()) {
                try {
                    await sleep(1500); // Brief pause for WA sync
                    if (WPP.group.setDescription) {
                        await withTimeout(
                            WPP.group.setDescription(groupId, description.trim()),
                            10000,
                            'Timeout setting group description'
                        );
                    }
                } catch (e) {
                    // Non-critical: log but don't fail
                    console.warn('⚠️ Could not set group description:', e.message);
                }
            }

            // --- Step 3: Set Group Icon (if provided) ---
            // SAFETY: Only use group-level APIs (setIcon / group.setProfilePic)
            // NEVER use WPP.profile.setProfilePic — it changes the user's personal photo
            if (base64Image) {
                try {
                    await sleep(1000);
                    if (WPP.group.setIcon) {
                        await withTimeout(
                            WPP.group.setIcon(groupId, base64Image),
                            15000,
                            'Timeout setting group icon'
                        );
                    } else if (WPP.group.setProfilePic) {
                        await withTimeout(
                            WPP.group.setProfilePic(groupId, base64Image),
                            15000,
                            'Timeout setting group profile pic'
                        );
                    } else {
                        console.warn('⚠️ No group icon API available (setIcon/setProfilePic). Skipping icon.');
                    }
                } catch (e) {
                    console.warn('⚠️ Could not set group icon:', e.message);
                }
            }

            // --- Step 4: Set group settings ---
            try {
                await sleep(500);
                // announce: true = only admins can send
                if (WPP.group.setProperty) {
                    if (sendPermission === 'admin') {
                        await WPP.group.setProperty(groupId, 'announcement', true);
                    }
                    if (addPermission === 'admin') {
                        await WPP.group.setProperty(groupId, 'restrict', true);
                    }
                }
            } catch (e) {
                console.warn('⚠️ Could not set group properties:', e.message);
            }

            // --- Phase 2: Send invites to privacy-blocked numbers (code===403 with invite_code) ---
            if (sendInviteOnFail) {
                const inviteTargets = Object.entries(results.details)
                    .filter(([, info]) => info.code === 403 && info.invite_code)
                    .map(([phone, info]) => ({ phone, invite_code: info.invite_code }));

                if (inviteTargets.length > 0) {
                    emitProgress({
                        stage: 'inviting',
                        status: 'active',
                        message: `📨 إرسال الدعوات لـ ${inviteTargets.length} رقم محجوب...`,
                        total: inviteTargets.length,
                        current: 0,
                        results: { ...results }
                    });

                    for (let j = 0; j < inviteTargets.length; j++) {
                        const { phone, invite_code } = inviteTargets[j];
                        const jid = phone + '@c.us';
                        try {
                            const inviteLink = `https://chat.whatsapp.com/${invite_code}`;
                            const inviteMsg = `مرحباً! 👋\nتم إنشاء مجموعة جديدة ونحب تنضم لينا.\n\n🔗 رابط الانضمام:\n${inviteLink}`;

                            if (WPP.chat && WPP.chat.sendTextMessage) {
                                await withTimeout(
                                    WPP.chat.sendTextMessage(jid, inviteMsg),
                                    15000,
                                    'Timeout sending invite message'
                                );
                            }
                            results.inviteSent++;
                            console.log(`📨 Invite sent: ${phone}`);
                        } catch (invErr) {
                            console.warn(`⚠️ Invite send failed for ${phone}:`, invErr.message);
                        }

                        emitProgress({
                            stage: 'inviting',
                            status: 'active',
                            current: j + 1,
                            total: inviteTargets.length,
                            percent: Math.floor(((j + 1) / inviteTargets.length) * 100),
                            message: `📨 إرسال الدعوة: ${j + 1}/${inviteTargets.length}...`,
                            results: { ...results }
                        });

                        // Small humanized delay between invite messages
                        if (j < inviteTargets.length - 1) {
                            await sleep(Math.random() * 2000 + 1500);
                        }
                    }
                }
            }

            // Final status
            emitProgress({
                stage: 'complete',
                status: 'done',
                message: `✅ تم الإنشاء: ${results.success} نجاح، ${results.failed} فشل، ${results.inviteSent} دعوة`,
                groupId: groupId,
                results: results
            });

            return {
                groupId: groupId,
                title: title,
                results: results
            };
        },

        // ----------------------------------------------------------
        // addMembersSmart()
        // Humanized one-by-one adding for EXISTING groups only.
        // Includes rate-overlimit detection with backoff strategy:
        //   1st hit  → wait 60s then retry
        //   2nd hit  → wait 120s then retry
        //   3rd hit  → stop entire campaign
        //
        // Wraps: WPP.group.addParticipants (module 7103)
        // Response codes from module 7103:
        //   200 = OK
        //   403 = Privacy blocked → capture invite_code
        //   409 = Already a member
        //   421 = Pending admin approval
        // ----------------------------------------------------------
        addMembersSmart: async function ({
            groupId,
            phoneNumbers = [],
            sendInviteOnFail = true,
            onProgress = null        // callback(progressData)
        }) {
            const WPP = await ensureWPPReady();

            if (!groupId) throw new Error('groupId is required');
            if (!phoneNumbers.length) throw new Error('No phone numbers provided');

            try {
                await WPP.chat.get(groupId);
                await sleep(2000);
            } catch (e) {
                console.warn('⚠️ WPP.chat.get warning:', e.message);
            }

            // Deduplicate
            const uniqueNumbers = [...new Set(phoneNumbers.map(n => n.replace(/\D/g, '')))];
            const total = uniqueNumbers.length;
            const results = {
                total: total,
                success: 0,
                failed: 0,
                alreadyMember: 0,
                pendingApproval: 0,
                privacyBlocked: 0,
                inviteSent: 0,
                errors: [],
                details: {}   // { [phone]: { code, message, invite_code } }
            };

            // Rate-overlimit backoff tracker
            let consecutiveRateLimits = 0;

            emitProgress({
                stage: 'adding',
                status: 'active',
                message: `جاري إضافة ${total} عضو...`,
                total: total,
                current: 0,
                results: results
            });

            // Process members ONE by ONE for maximum safety
            for (let i = 0; i < total; i++) {
                const phone = uniqueNumbers[i];
                const jid = phone + '@c.us';

                try {
                    // Call WPP.group.addParticipants with a SINGLE member with a timeout of 15 seconds
                    // Module 7103 returns: { [wid]: { wid, code, message, invite_code, invite_code_exp } }
                    const addResult = await withTimeout(
                        WPP.group.addParticipants(groupId, [jid]),
                        15000,
                        'Timeout: WhatsApp servers did not respond in 15 seconds'
                    );

                    // Process result
                    let code = -1, inviteCode = null, message = '';

                    if (addResult && typeof addResult === 'object') {
                        // Find the result for this participant using JID, then phone, then fallback to first key
                        let info = addResult[jid] || addResult[phone];

                        // Fallback
                        if (!info) {
                            const keys = Object.keys(addResult);
                            if (keys.length > 0) info = addResult[keys[0]];
                        }

                        if (info) {
                            code = Number(info.code || info.error || -1);
                            inviteCode = info.invite_code || null;
                            message = info.message || '';
                        }
                    }

                    results.details[phone] = { code, message, invite_code: inviteCode };

                    if (code === 200) {
                        results.success++;
                        consecutiveRateLimits = 0; // Reset on any success
                        console.log(`✅ Added: ${phone}`);
                    } else if (code === 403) {
                        results.privacyBlocked++;
                        results.failed++;
                        consecutiveRateLimits = 0;
                        // Do NOT send invite now — collect for batch invite phase at the end
                        console.log(`🔒 Privacy blocked: ${phone} — سيتم إرسال الدعوة لاحقاً`);
                    } else if (code === 409) {
                        results.alreadyMember++;
                        consecutiveRateLimits = 0;
                        console.log(`ℹ️ Already member: ${phone}`);
                    } else if (code === 421) {
                        results.pendingApproval++;
                        consecutiveRateLimits = 0;
                    } else {
                        results.failed++;
                        results.errors.push({ phone, code, message });
                        consecutiveRateLimits = 0;
                        console.warn(`❌ Failed (${code}): ${phone} - ${message}`);
                    }

                } catch (err) {
                    const errMsg = err.message || '';

                    // --- Rate-overlimit detection and backoff ---
                    const isRateLimit = errMsg.includes('rate-overlimit')
                        || errMsg.includes('rate_overlimit')
                        || errMsg.includes('overlimit');

                    if (isRateLimit) {
                        consecutiveRateLimits++;
                        console.warn(`⚠️ Rate limit hit (${consecutiveRateLimits}x consecutive) at ${phone}`);

                        if (consecutiveRateLimits >= 3) {
                            // 3rd consecutive rate limit → stop entire campaign
                            emitProgress({
                                stage: 'complete',
                                status: 'rate_limit_stop',
                                message: `🛑 تم إيقاف الحملة: rate limit متكرر (${consecutiveRateLimits} مرات متتالية)`,
                                results: { ...results }
                            });
                            return results;
                        }

                        // 1st hit → 60s, 2nd hit → 120s
                        const waitSeconds = consecutiveRateLimits === 1 ? 60 : 120;
                        emitProgress({
                            stage: 'waiting',
                            status: 'active',
                            message: `⏳ rate limit — انتظار ${waitSeconds} ثانية قبل إعادة المحاولة...`,
                            delayMs: waitSeconds * 1000
                        });
                        await sleep(waitSeconds * 1000);

                        // Retry this same member (decrement i so the loop re-processes it)
                        i--;
                        continue;
                    }

                    // Non-rate-limit error
                    results.failed++;
                    results.errors.push({ phone, code: -1, message: errMsg });
                    results.details[phone] = { code: -1, message: errMsg, invite_code: null };
                    consecutiveRateLimits = 0;
                    console.warn(`❌ Exception adding ${phone}:`, errMsg);
                }

                // Emit progress after each member
                const progressData = {
                    stage: 'adding',
                    status: 'active',
                    current: i + 1,
                    total: total,
                    percent: Math.floor(((i + 1) / total) * 100),
                    results: { ...results },
                    message: `إضافة الأعضاء: ${i + 1}/${total}...`
                };
                emitProgress(progressData);
                if (onProgress) onProgress(progressData);

                // Humanizer delay between members (skip if last)
                if (i < total - 1) {
                    const delay = getHumanizerDelay(i);
                    emitProgress({
                        stage: 'waiting',
                        status: 'active',
                        message: `⏳ انتظار ${Math.round(delay / 1000)}ث للحماية...`,
                        delayMs: delay
                    });
                    await sleep(delay);
                }
            }

            // -------------------------------------------------------
            // Phase 2: Send invites to ALL privacy-blocked numbers
            // collected during Phase 1 above.
            // Only runs when sendInviteOnFail option is enabled.
            // -------------------------------------------------------
            if (sendInviteOnFail) {
                const inviteTargets = Object.entries(results.details)
                    .filter(([, info]) => info.code === 403 && info.invite_code)
                    .map(([phone, info]) => ({ phone, invite_code: info.invite_code }));

                if (inviteTargets.length > 0) {
                    emitProgress({
                        stage: 'inviting',
                        status: 'active',
                        message: `📨 إرسال الدعوات لـ ${inviteTargets.length} رقم محجوب...`,
                        total: inviteTargets.length,
                        current: 0,
                        results: { ...results }
                    });

                    for (let j = 0; j < inviteTargets.length; j++) {
                        const { phone, invite_code } = inviteTargets[j];
                        const jid = phone + '@c.us';
                        try {
                            const inviteLink = `https://chat.whatsapp.com/${invite_code}`;
                            const inviteMsg = `مرحباً! 👋\nتم إنشاء مجموعة جديدة ونحب تنضم لينا.\n\n🔗 رابط الانضمام:\n${inviteLink}`;

                            if (WPP.chat && WPP.chat.sendTextMessage) {
                                await withTimeout(
                                    WPP.chat.sendTextMessage(jid, inviteMsg),
                                    15000,
                                    'Timeout sending invite message'
                                );
                            }
                            results.inviteSent++;
                            console.log(`📨 Invite sent: ${phone}`);
                        } catch (invErr) {
                            console.warn(`⚠️ Invite send failed for ${phone}:`, invErr.message);
                        }

                        emitProgress({
                            stage: 'inviting',
                            status: 'active',
                            current: j + 1,
                            total: inviteTargets.length,
                            percent: Math.floor(((j + 1) / inviteTargets.length) * 100),
                            message: `📨 إرسال الدعوة: ${j + 1}/${inviteTargets.length}...`,
                            results: { ...results }
                        });

                        // Small humanized delay between invite messages
                        if (j < inviteTargets.length - 1) {
                            await sleep(Math.random() * 2000 + 1500);
                        }
                    }
                }
            }

            // Final status — ALWAYS emit complete
            emitProgress({
                stage: 'complete',
                status: 'done',
                message: `✅ تمت الإضافة: ${results.success} نجاح، ${results.failed} فشل، ${results.inviteSent} دعوة أُرسلت`,
                results: results
            });

            return results;
        },

        // ----------------------------------------------------------
        // createGroupAndAddMembers()
        // Simple wrapper: validates input then delegates entirely
        // to createNewGroupFull() which handles everything in one shot.
        // ----------------------------------------------------------
        createGroupAndAddMembers: async function (config) {
            const {
                title,
                description = '',
                base64Image = null,
                phoneNumbers = [],
                sendPermission = 'admin',
                addPermission = 'admin',
                sendInviteOnFail = true
            } = config;

            // Validation
            if (!phoneNumbers || phoneNumbers.length === 0) {
                throw new Error('لا يمكن إنشاء مجموعة فارغة، يجب تحديد عضو واحد على الأقل');
            }
            if (phoneNumbers.length > 1024) {
                throw new Error('الحد الأقصى لعدد الأعضاء هو 1024');
            }

            // Delegate entirely to createNewGroupFull — it handles
            // group creation with all participants in a single WPP.group.create call,
            // result processing, and Phase 2 invites internally.
            const result = await this.createNewGroupFull({
                title,
                participants: phoneNumbers,
                description,
                base64Image,
                sendPermission,
                addPermission,
                sendInviteOnFail
            });

            return {
                groupId: result.groupId,
                title: result.title,
                results: result.results
            };
        },

        // ----------------------------------------------------------
        // getGroupInviteLink()
        // Fetches the invite link for a group
        // ----------------------------------------------------------
        getGroupInviteLink: async function (groupId) {
            const WPP = await ensureWPPReady();
            try {
                if (WPP.group.getInviteCode) {
                    const code = await WPP.group.getInviteCode(groupId);
                    return `https://chat.whatsapp.com/${code}`;
                }
            } catch (e) {
                console.warn('⚠️ Could not get invite link:', e.message);
            }
            return null;
        }
    };

    // ============================================================
    // Message Listener (receives commands from panel.js)
    // ============================================================
    function setupGMMessageListener() {
        window.addEventListener('message', async (event) => {
            const data = event.data;
            if (!data || !data.type) return;

            switch (data.type) {

                // Fetch managed groups for the "Add Members" dropdown
                case 'GM_GET_MANAGED_GROUPS': {
                    try {
                        const groups = await GroupManagerService.getManagedGroups();
                        window.postMessage({
                            type: 'GM_MANAGED_GROUPS_RESULT',
                            status: 'success',
                            data: groups
                        }, '*');
                    } catch (err) {
                        emitProgress({ stage: 'complete', status: 'error', message: err.message });
                        window.postMessage({
                            type: 'GM_MANAGED_GROUPS_RESULT',
                            status: 'error',
                            message: err.message
                        }, '*');
                    }
                    break;
                }

                // Create group + add members full flow
                case 'GM_CREATE_GROUP': {
                    try {
                        const result = await GroupManagerService.createGroupAndAddMembers({
                            title: data.title,
                            description: data.description || '',
                            base64Image: data.base64Image || null,
                            phoneNumbers: data.phoneNumbers || [],
                            sendPermission: data.sendPermission || 'admin',
                            addPermission: data.addPermission || 'admin',
                            sendInviteOnFail: data.sendInviteOnFail !== false
                        });
                        window.postMessage({
                            type: 'GM_CREATE_GROUP_RESULT',
                            status: 'success',
                            data: result
                        }, '*');
                    } catch (err) {
                        emitProgress({ stage: 'complete', status: 'error', message: err.message });
                        window.postMessage({
                            type: 'GM_CREATE_GROUP_RESULT',
                            status: 'error',
                            message: err.message
                        }, '*');
                    }
                    break;
                }

                // Add members to existing group
                case 'GM_ADD_MEMBERS': {
                    try {
                        const result = await GroupManagerService.addMembersSmart({
                            groupId: data.groupId,
                            phoneNumbers: data.phoneNumbers || [],
                            sendInviteOnFail: data.sendInviteOnFail !== false
                        });
                        window.postMessage({
                            type: 'GM_ADD_MEMBERS_RESULT',
                            status: 'success',
                            data: result
                        }, '*');
                    } catch (err) {
                        emitProgress({ stage: 'complete', status: 'error', message: err.message });
                        window.postMessage({
                            type: 'GM_ADD_MEMBERS_RESULT',
                            status: 'error',
                            message: err.message
                        }, '*');
                    }
                    break;
                }

                // Get invite link for a group
                case 'GM_GET_INVITE_LINK': {
                    try {
                        const link = await GroupManagerService.getGroupInviteLink(data.groupId);
                        window.postMessage({
                            type: 'GM_INVITE_LINK_RESULT',
                            status: 'success',
                            data: { link }
                        }, '*');
                    } catch (err) {
                        emitProgress({ stage: 'complete', status: 'error', message: err.message });
                        window.postMessage({
                            type: 'GM_INVITE_LINK_RESULT',
                            status: 'error',
                            message: err.message
                        }, '*');
                    }
                    break;
                }
            }
        });
    }

    // ============================================================
    // Initialization: Wait for WPP then set up listener
    // ============================================================
    async function initGroupManager() {
        let attempts = 0;
        while (attempts < 120) {
            const engine = getWPP();
            const humanizer = window.Humanizer;

            if (engine && humanizer) {
                setupGMMessageListener();
                window.GroupManagerService = GroupManagerService;
                window.postMessage({ type: 'GM_SERVICE_READY' }, '*');
                return;
            }
            await sleep(1000);
            attempts++;
        }
        console.warn('⚠️ GroupManagerService: Timeout waiting for dependencies');
    }

    initGroupManager();

})();
